// load wavefront object file. adds terminating \n so last line of file can be correctly parsed as a 'line' later // basic loader - only deals with vertices v, texcoords vt, normals vn // - only copes with triangular meshes (no quads) // - doesn't deal with textures or materials int ObjFileModel::loadfile(char* fname) { FILE* pFile; pFile = fopen(fname , "r"); // if changed to bin format will read carriage return \r (0d) as well as \n (0a) into fbuffer, may need to add \r checks(but seemed to work with basic test) if (pFile==NULL) { DXTRACE_MSG("Failed to open model file");DXTRACE_MSG(fname); return 0 ;} // get file size fseek(pFile, 0, SEEK_END); fbuffersize = ftell(pFile); rewind(pFile); // allocate memory for entire file size fbuffer = new char[fbuffersize+1]; // 1 added to cope with adding a \n later in case file doesn't end with \n if (fbuffer == NULL) {fclose(pFile); DXTRACE_MSG("Failed allocate memory for model file");DXTRACE_MSG(fname); return 0 ;} // copy file into memory actualsize = fread(fbuffer,1,fbuffersize,pFile); // actualsize may be less than fbuffersize in text mode as \r are stripped if (actualsize == 0) {fclose(pFile); DXTRACE_MSG("Failed to read model file");DXTRACE_MSG(fname); return 0 ;} // add a newline at end in case file does not, so can deal with whole buffer as a set of lines of text fbuffer[actualsize] = '\n'; fclose(pFile); return 1; }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- DWORD CDPlay8Client::GetSPBuffer() { HRESULT hr = DPN_OK; DPN_SP_CAPS dnSPCaps; DWORD dwFlags = NULL; DWORD dwSPBufferSize = NULL; DXTRACE_MSG( TEXT("Attempting to Get SP Buffer Size.") ); dnSPCaps.dwSize = sizeof(DPN_SP_CAPS); hr = m_pDPlay->GetSPCaps(&CLSID_DP8SP_TCPIP, &dnSPCaps, dwFlags); if(hr != DPN_OK) { DXTRACE_ERR( TEXT("GetSPCaps error"), hr ); dwSPBufferSize = 0xffffffff; } else { dwSPBufferSize = dnSPCaps.dwSystemBufferSize; } return dwSPBufferSize; }
// ------------------------------------------------------ // create blend state // ------------------------------------------------------ RID BlendStateParser::createBlendState(const char* name, const BlendStateDescriptor& descriptor) { D3D11_BLEND_DESC blendDesc; ZeroMemory(&blendDesc, sizeof(blendDesc)); if (descriptor.alphaEnabled) { blendDesc.RenderTarget[0].BlendEnable = TRUE; } else { blendDesc.RenderTarget[0].BlendEnable = FALSE; //blendDesc.RenderTarget[0].BlendEnable = (srcBlend != D3D11_BLEND_ONE) || (destBlend != D3D11_BLEND_ZERO); } blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlend = BLEND_STATE_MAPPINGS[descriptor.srcBlend].blend; blendDesc.RenderTarget[0].DestBlend = BLEND_STATE_MAPPINGS[descriptor.destBlend].blend; blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlendAlpha = BLEND_STATE_MAPPINGS[descriptor.srcAlphaBlend].blend; blendDesc.RenderTarget[0].DestBlendAlpha = BLEND_STATE_MAPPINGS[descriptor.destAlphaBlend].blend; blendDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; ID3D11BlendState* state; HRESULT d3dResult = _resCtx->device->CreateBlendState(&blendDesc, &state); if (FAILED(d3dResult)) { DXTRACE_MSG("Failed to create blendstate!"); return INVALID_RID; } BlendStateResource* cbr = new BlendStateResource(state); _resCtx->resources.push_back(cbr); return create(name, ResourceType::BLENDSTATE); }
bool ParticleManager::CompileShader(ID3DBlob** shader, string filename, string entry, string shaderModel) { DWORD shaderFlags = 0; ID3DBlob* errorBuffer = 0; HRESULT hResult; //If debugging then compile shader in debug mode for error messages #if defined(DEBUG) || defined(_DEBUG) shaderFlags |= D3DCOMPILE_DEBUG; #endif //Compile the shader using the determined filename, entry point, shader model hResult = D3DX11CompileFromFile(filename.c_str(), 0, 0, entry.c_str(), shaderModel.c_str(), shaderFlags, 0, 0, shader, &errorBuffer, 0); //If the returned shader has errored then see what line in the .fx file if (errorBuffer != 0) { MessageBoxA(NULL, (char*)errorBuffer->GetBufferPointer(), 0, 0); errorBuffer->Release(); errorBuffer = 0; } //If the compile failed completely then return a DXTRACE msg to link back to this function call if (FAILED(hResult)) { DXTRACE_MSG(__FILE__, (DWORD)__LINE__, hResult, "D3DX11CompileFromFile", true); return false; } return true; }
void CBGMusic::Load(LPCTSTR filename) { Release(); HRESULT hr = CoCreateInstance( CLSID_FilterGraph, // COMの識別子 NULL, // 特別に取得する情報はないのでNULL CLSCTX_INPROC_SERVER, // このプログラム内でのみ使うことを指定 IID_IGraphBuilder, // 取得するインターフェース (LPVOID*)&pBuilder); // 格納先 if(FAILED(hr)){ DXTRACE_MSG(_T("IGraphBuilderの作成に失敗しました")); return; } #ifdef _UNICODE pBuilder->RenderFile(filename, NULL); #else wchar_t wfname[MAX_PATH]; MultiByteToWideChar(CP_ACP, 0, filename, -1, wfname, MAX_PATH); pBuilder->RenderFile(wfname, NULL); #endif pBuilder->QueryInterface(IID_IMediaControl, (LPVOID*)&pMediaCtrl); pBuilder->QueryInterface(IID_IMediaSeeking, (LPVOID*)&pMediaSeeking); pBuilder->QueryInterface(IID_IBasicAudio, (LPVOID*)&pBasicAudio); }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- DWORD CDPlay8Client::GetNumSPThreads() { HRESULT hr = DPN_OK; DPN_SP_CAPS dnSPCaps; DWORD dwFlags = NULL; DWORD dwNumSPThreads = NULL; DXTRACE_MSG( TEXT("Attempting to Get SP Thread Count.") ); dnSPCaps.dwSize = sizeof(DPN_SP_CAPS); hr = m_pDPlay->GetSPCaps(&CLSID_DP8SP_TCPIP, &dnSPCaps, dwFlags); if(hr != DPN_OK) { DXTRACE_ERR( TEXT("GetSPCaps error"), hr ); dwNumSPThreads = 0; } else { dwNumSPThreads = dnSPCaps.dwNumThreads; } return dwNumSPThreads; }
BOOL CMyLib::Initialize(HWND hWnd, HINSTANCE hInstance){ this->hWnd = hWnd; this->hInstance = hInstance; pD3D = Direct3DCreate9(D3D_SDK_VERSION); if (pD3D == NULL){ DXTRACE_MSG(_T("DirectXDeviceの初期化に失敗しました")); return FALSE; } D3DDISPLAYMODE d3ddm; if (FAILED(pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm))){ DXTRACE_MSG(_T("DirectX3DDeviceの初期化に失敗しました")); return FALSE; } D3DPRESENT_PARAMETERS d3dpp; ZeroMemory(&d3dpp, sizeof(d3dpp)); d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; if (FAILED(pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &pD3Ddevice))){ DXTRACE_MSG(_T("3DDeviceObjectの初期化に失敗ました")); return FALSE; } pD3Ddevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); pD3Ddevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); pD3Ddevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); if (FAILED(D3DXCreateSprite(pD3Ddevice, &pSprite))){ DXTRACE_MSG(_T("SpriteObjectの作成に失敗しました")); return FALSE; } return TRUE; }
/*-------------------------------------------- メイン ---------------------------------------------*/ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int) { // デバッグ ヒープ マネージャによるメモリ割り当ての追跡方法を設定 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // XNA Mathライブラリのサポート チェック if (XMVerifyCPUSupport() != TRUE) { DXTRACE_MSG(L"WinMain XMVerifyCPUSupport"); return 0; } // アプリケーションに関する初期化 HRESULT hr = InitApp(hInst); if (FAILED(hr)) { DXTRACE_ERR(L"WinMain InitApp", hr); return 0; } // Direct3Dの初期化 hr = InitDirect3D(); if (FAILED(hr)) { DXTRACE_ERR(L"WinMain InitDirect3D", hr); CleanupDirect3D(); CleanupApp(); return 0; } // メッセージ ループ MSG msg; do { if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { // アイドル処理 if (!AppIdle()) // エラーがある場合,アプリケーションを終了する DestroyWindow(g_hWindow); } } while (msg.message != WM_QUIT); // アプリケーションの終了処理 CleanupApp(); return (int)msg.wParam; }
// sets up the vertex positions and texture coordinates and draws the sprite bool SpriteSheet::DrawSprite( float texX, float texY, float texWidth, float texHeight, float sheetWidth, float sheetHeight, ID3D11DeviceContext* d3dContext, ID3D11Buffer* vertexBuffer ) { // texture's width on screen float widthOnScreen = texWidth / game_->GetScreenWidth( ); // texture's height on screen float heightOnScreen = texHeight / game_->GetScreenHeight( ); // texture's texel width float texelWidth = texWidth / sheetWidth; // texture's texel height float texelHeight = texHeight / sheetHeight; D3D11_MAPPED_SUBRESOURCE mapResource; HRESULT d3dResult = d3dContext->Map( vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapResource ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to map resource!" ); return false; } // point to our vertex buffer's internal data VertexPos *spritePtr = ( VertexPos* )mapResource.pData; // set the vertex positions spritePtr[0].pos = XMFLOAT3( texWidth / 2, texHeight / 2, 1.0f ); spritePtr[1].pos = XMFLOAT3( texWidth / 2, -texHeight / 2, 1.0f ); spritePtr[2].pos = XMFLOAT3( -texWidth / 2, texHeight / 2, 1.0f ); spritePtr[3].pos = XMFLOAT3( -texWidth / 2, -texHeight / 2, 1.0f ); // align the texture spritePtr[0].tex0 = XMFLOAT2( texelWidth * ( texX + 1 ), texelHeight * texY ); spritePtr[1].tex0 = XMFLOAT2( texelWidth * ( texX + 1 ), texelHeight * ( texY + 1 ) ); spritePtr[2].tex0 = XMFLOAT2( texelWidth * texX, texelHeight * texY ); spritePtr[3].tex0 = XMFLOAT2( texelWidth * texX, texelHeight * ( texY + 1 ) ); // unmap the buffer and draw all the vertices d3dContext->Unmap( vertexBuffer, 0 ); d3dContext->Draw( 4, 0 ); activate_ = false; return true; }
//George Anderson /////draws a rectangle to screen bool ModelsDemo::DrawRect() { ////////////////// D3D11_MAPPED_SUBRESOURCE mapResource; HRESULT d3dResult = d3dContext_->Map( textVertexBuffer_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapResource ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to map resource!" ); return false; } // Point to our vertex buffer's internal data. TextVertexPos *spritePtr = ( TextVertexPos* )mapResource.pData; spritePtr[0].pos = XMFLOAT3( -1.0f, 1.0f, 1.0f ); spritePtr[1].pos = XMFLOAT3( 1.0f, 1.0f, 1.0f ); spritePtr[2].pos = XMFLOAT3( -1.0f, -1.0f, 1.0f ); spritePtr[3].pos = XMFLOAT3( 1.0f, 1.0f, 1.0f ); spritePtr[4].pos = XMFLOAT3( 1.0f, -1.0f, 1.0f ); spritePtr[5].pos = XMFLOAT3( -1.0f, -1.0f, 1.0f ); spritePtr[0].tex0 = XMFLOAT2( 0.0f, 0.0f ); spritePtr[1].tex0 = XMFLOAT2( 1.0f, 0.0f ); spritePtr[2].tex0 = XMFLOAT2( 0.0f, 1.0f ); spritePtr[3].tex0 = XMFLOAT2( 1.0f, 0.0f ); spritePtr[4].tex0 = XMFLOAT2( 1.0f, 1.0f ); spritePtr[5].tex0 = XMFLOAT2( 0.0f, 1.0f ); d3dContext_->Unmap( textVertexBuffer_, 0 ); d3dContext_->Draw( 6, 0 ); return true; }
// ------------------------------------------------------ // cretate quad index buffer // ------------------------------------------------------ RID QuadIndexBufferParser::createQuadIndexBuffer(const char* name, const QuadIndexBufferDescriptor& descriptor) { // FIXME: check that size % 6 == 0 !!! D3D11_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.CPUAccessFlags = 0; bufferDesc.ByteWidth = sizeof(uint32_t) * descriptor.size; bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bufferDesc.MiscFlags = 0; uint32_t* data = new uint32_t[descriptor.size]; int base = 0; int cnt = 0; int num = descriptor.size / 6; for (int i = 0; i < num; ++i) { data[base] = cnt; data[base + 1] = cnt + 1; data[base + 2] = cnt + 3; data[base + 3] = cnt + 1; data[base + 4] = cnt + 2; data[base + 5] = cnt + 3; base += 6; cnt += 4; } // Define the resource data. D3D11_SUBRESOURCE_DATA InitData; InitData.pSysMem = data; InitData.SysMemPitch = 0; InitData.SysMemSlicePitch = 0; // Create the buffer with the device. ID3D11Buffer* buffer; HRESULT hr = _resCtx->device->CreateBuffer(&bufferDesc, &InitData, &buffer); if (FAILED(hr)) { delete[] data; DXTRACE_MSG("Failed to create quad index buffer!"); return -1; } delete[] data; IndexBufferResource* cbr = new IndexBufferResource(buffer); _resCtx->resources.push_back(cbr); return create(name, ResourceType::INDEXBUFFER); }
void CBGMusic::Fade(DWORD endtime, LONG volume) { if(!pBasicAudio){ DXTRACE_MSG(_T("ボリュームの設定ができません。")); return; } bFading = TRUE; LONG v; pBasicAudio->get_Volume(&v); vol_s = (float)v; float vol_e = (float)volume; time_s = (float)timeGetTime(); time_e = (float)endtime; delta = (vol_e - vol_s) / time_e; }
RID IndexBufferParser::createIndexBuffer(const char* name, const IndexBufferDescriptor& descriptor) { D3D11_BUFFER_DESC bufferDesc; if (descriptor.dynamic) { bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; } else { bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.CPUAccessFlags = 0; } bufferDesc.ByteWidth = sizeof(uint32_t) * descriptor.size; bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bufferDesc.MiscFlags = 0; ID3D11Buffer* buffer; HRESULT hr = _resCtx->device->CreateBuffer(&bufferDesc, 0, &buffer); if (FAILED(hr)) { DXTRACE_MSG("Failed to create index buffer!"); return -1; } IndexBufferResource* cbr = new IndexBufferResource(buffer); _resCtx->resources.push_back(cbr); return create(name, ResourceType::INDEXBUFFER); }
bool SplashScreen::LoadContent( ) { ID3DBlob* vsBuffer = 0; // compile the vertex shader from fx file bool compileResult = game_->CompileD3DShader( "TextureMap_Sprites.fx", "VS_Main", "vs_4_0", &vsBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling the vertex shader!" ); return false; } HRESULT d3dResult; // create the vertex shader d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), 0, &solidColorVS_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the vertex shader!" ); if( vsBuffer ) vsBuffer->Release( ); return false; } D3D11_INPUT_ELEMENT_DESC solidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout ); // create the input layout d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ ); vsBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the input layout!" ); return false; } ID3DBlob* psBuffer = 0; // compile the pixel shader from fx file compileResult = game_->CompileD3DShader( "TextureMap_Sprites.fx", "PS_Main", "ps_4_0", &psBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling pixel shader!" ); return false; } // create the pixel shader d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ), psBuffer->GetBufferSize( ), 0, &solidColorPS_ ); psBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating pixel shader!" ); return false; } // load the texture image d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "Assets/Images/Menu.png", 0, 0, &colorMap_, 0 ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to load the texture image!" ); return false; } D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) ); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; // create the sampler state d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc, &colorMapSampler_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create color map sampler state!" ); return false; } ID3D11Resource* colorTex; colorMap_->GetResource( &colorTex ); D3D11_TEXTURE2D_DESC colorTexDesc; ( ( ID3D11Texture2D* )colorTex )->GetDesc( &colorTexDesc ); colorTex->Release( ); float halfWidth = ( float )colorTexDesc.Width / 2.0f; float halfHeight = ( float )colorTexDesc.Height / 2.0f; D3D11_BUFFER_DESC vertexDesc; ZeroMemory( &vertexDesc, sizeof( vertexDesc ) ); vertexDesc.Usage = D3D11_USAGE_DYNAMIC; vertexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof( VertexPos ) * 4; // create the vertex buffer d3dResult = d3dDevice_->CreateBuffer( &vertexDesc, 0, &vertexBuffer_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create vertex buffer!" ); return false; } D3D11_BUFFER_DESC constDesc; ZeroMemory( &constDesc, sizeof( constDesc ) ); constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constDesc.ByteWidth = sizeof( XMMATRIX ); constDesc.Usage = D3D11_USAGE_DEFAULT; // create the constant buffer d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &mvpCB_ ); if( FAILED( d3dResult ) ) { return false; } // load the sprite sheet with sprite names and coordinates spriteSheet_ = new SpriteSheet( game_, 3, 6, ( float )colorTexDesc.Width, ( float )colorTexDesc.Height ); spriteWidth_ = spriteSheet_->GetSheetWidth( ) / spriteSheet_->GetHorizontalSprites( ); spriteHeight_ = spriteSheet_->GetSheetHeight( ) / spriteSheet_->GetVerticalSprites( ); // add coordinates to animations vector<XMFLOAT2> menu; menu.push_back( XMFLOAT2( 0.0f, 0.0f ) ); spriteSheet_->AddAnimationToMap( "menu" , menu, -1 ); vector<XMFLOAT2> menu_play; menu_play.push_back( XMFLOAT2( 1.0f, 0.0f ) ); spriteSheet_->AddAnimationToMap( "menu_play" , menu_play, -1 ); vector<XMFLOAT2> menu_instructions; menu_instructions.push_back( XMFLOAT2( 0.0f, 1.0f ) ); spriteSheet_->AddAnimationToMap( "menu_instructions" , menu_instructions, -1 ); vector<XMFLOAT2> menu_credits; menu_credits.push_back( XMFLOAT2( 1.0f, 1.0f ) ); spriteSheet_->AddAnimationToMap( "menu_credits" , menu_credits, -1 ); vector<XMFLOAT2> menu_exit; menu_exit.push_back( XMFLOAT2( 0.0f, 2.0f ) ); spriteSheet_->AddAnimationToMap( "menu_exit" , menu_exit, -1 ); vector<XMFLOAT2> instructions; instructions.push_back( XMFLOAT2( 1.0f, 2.0f ) ); spriteSheet_->AddAnimationToMap( "instructions" , instructions, -1 ); vector<XMFLOAT2> instructions_back; instructions_back.push_back( XMFLOAT2( 0.0f, 3.0f ) ); spriteSheet_->AddAnimationToMap( "instructions_back" , instructions_back, -1 ); vector<XMFLOAT2> credits; credits.push_back( XMFLOAT2( 1.0f, 3.0f ) ); spriteSheet_->AddAnimationToMap( "credits" , credits, -1 ); vector<XMFLOAT2> credits_back; credits_back.push_back( XMFLOAT2( 0.0f, 4.0f ) ); spriteSheet_->AddAnimationToMap( "credits_back" , credits_back, -1 ); vector<XMFLOAT2> game_over; game_over.push_back( XMFLOAT2( 1.0f, 4.0f ) ); spriteSheet_->AddAnimationToMap( "game_over" , game_over, -1 ); vector<XMFLOAT2> game_over_replay; game_over_replay.push_back( XMFLOAT2( 0.0f, 5.0f ) ); spriteSheet_->AddAnimationToMap( "game_over_replay" , game_over_replay, -1 ); vector<XMFLOAT2> game_over_menu; game_over_menu.push_back( XMFLOAT2( 1.0f, 5.0f ) ); spriteSheet_->AddAnimationToMap( "game_over_menu" , game_over_menu, -1 ); vector<XMFLOAT2> victory; victory.push_back( XMFLOAT2( 2.0f, 0.0f ) ); spriteSheet_->AddAnimationToMap( "victory" , victory, -1 ); vector<XMFLOAT2> victory_replay; victory_replay.push_back( XMFLOAT2( 2.0f, 1.0f ) ); spriteSheet_->AddAnimationToMap( "victory_replay" , victory_replay, -1 ); vector<XMFLOAT2> victory_back; victory_back.push_back( XMFLOAT2( 2.0f, 2.0f ) ); spriteSheet_->AddAnimationToMap( "victory_back" , victory_back, -1 ); // create sprite menu sprite_ = spriteSheet_->CreateSprite( collisionTemplate_, spriteWidth_, spriteHeight_, 0.0f, XMFLOAT2( game_->GetScreenWidth( ) / 2, game_->GetScreenHeight( ) / 2 ) ); sprite_.SetCurrentAnimation( "menu" ); // load button positions on splash screen play_ = XMFLOAT4( 500.0f, 595.0f, game_->GetScreenHeight( ) - 391.0f, game_->GetScreenHeight( ) - 330.0f ); instructions_ = XMFLOAT4( 500.0f, 762.0f, game_->GetScreenHeight( ) - 451.0f, game_->GetScreenHeight( ) - 390.0f ); credits_ = XMFLOAT4( 500.0f, 652.0f, game_->GetScreenHeight( ) - 511.0f, game_->GetScreenHeight( ) - 450.0f ); exit_ = XMFLOAT4( 500.0f, 586.0f, game_->GetScreenHeight( ) - 571.0f, game_->GetScreenHeight( ) - 510.0f ); replay_ = XMFLOAT4( 84.0f, 235.0f, game_->GetScreenHeight( ) - 577.0f, game_->GetScreenHeight( ) - 506.0f ); menu_ = XMFLOAT4( 611.0f, 721.0f, game_->GetScreenHeight( ) - 570.0f, game_->GetScreenHeight( ) - 509.0f ); back_ = XMFLOAT4( 616.0f, 722.0f, game_->GetScreenHeight( ) - 560.0f, game_->GetScreenHeight( ) - 499.0f ); // load mouse cursor if( !mouseCursor_->LoadContent( ) ) return false; // load score if( !score_->LoadContent( ) ) return false; Initialize( ); return true; }
bool DemoBase::Initialize(HINSTANCE hInstance, HWND hwnd) { hInstance_ = hInstance; hwnd_ = hwnd; RECT dimensions; GetClientRect(hwnd, &dimensions); unsigned int width = dimensions.right - dimensions.left; unsigned int height = dimensions.bottom - dimensions.top; D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE }; unsigned int totalDriverTypes = ARRAYSIZE( driverTypes ); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; unsigned int totalFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; swapChainDesc.Windowed = true; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; unsigned int creationFlags = 0; #ifdef _DEBUG creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT result; unsigned int driver = 0; for (; driver < totalDriverTypes; ++driver) { result = D3D11CreateDeviceAndSwapChain(0, driverTypes[driver], 0, creationFlags, featureLevels, totalFeatureLevels, D3D11_SDK_VERSION, &swapChainDesc, &swapChain_, &d3dDevice_, &featureLevel_, &d3dContext_); if (SUCCEEDED(result)) { driverType_ = driverTypes[driver]; break; } } if (FAILED(result)) { DXTRACE_MSG(L"Failed to create the Direct3D device!"); return false; } ID3D11Texture2D* backBufferTexture; result = swapChain_->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferTexture); if (FAILED(result)) { DXTRACE_MSG(L"Failed to get the swap chain back buffer!"); return false; } result = d3dDevice_->CreateRenderTargetView(backBufferTexture, 0, &backBufferTarget_); if (backBufferTexture) backBufferTexture->Release(); if (FAILED(result)) { DXTRACE_MSG(L"Failed to create the render target view!"); return false; } d3dContext_->OMSetRenderTargets(1, &backBufferTarget_, 0); D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>(width); viewport.Height = static_cast<float>(height); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; d3dContext_->RSSetViewports(1, &viewport); return LoadContent(); }
bool ColorInversionDemo::LoadContent() { ID3DBlob * buffer = 0; //ColorInversionDemo //bool compileResult = CompileD3DShader( "ColorInversion.fx" , 0 , "fx_5_0" , &buffer ); //ColorShiftingDemo bool compileResult = CompileD3DShader( "ColorShift.fx" , 0 , "fx_5_0" , &buffer ); if( compileResult == false ) { DXTRACE_MSG( "±àÒëeffect shader ʧ°Ü£¡" ); return false; } HRESULT d3dResult ; d3dResult = D3DX11CreateEffectFromMemory( buffer ->GetBufferPointer() , buffer ->GetBufferSize() , 0 , d3dDevice_ , &effect_ ); if( FAILED( d3dResult )) { DXTRACE_MSG( "´´½¨effect shader ʧ°Ü£¡" ); if( buffer ) { buffer ->Release(); } return false; } D3D11_INPUT_ELEMENT_DESC solidColorLayout[ ] = { { "POSITION" , 0 , DXGI_FORMAT_R32G32B32_FLOAT , 0 , 0 , D3D11_INPUT_PER_VERTEX_DATA , 0 } , { "TEXTURE" , 0 , DXGI_FORMAT_R32G32_FLOAT , 0 , 12 , D3D11_INPUT_PER_VERTEX_DATA , 0 } }; unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout ); ID3DX11EffectTechnique * colorInvTechnique; /*** //ColorInversionDemo colorInvTechnique = effect_ ->GetTechniqueByName( "ColorInversion" ); ID3DX11EffectPass * effectPass = colorInvTechnique ->GetPassByIndex( 0 ); */ colorInvTechnique = effect_ ->GetTechniqueByName( "ColorShift" ); ID3DX11EffectPass * effectPass = colorInvTechnique ->GetPassByIndex( 0 ); D3DX11_PASS_SHADER_DESC passDesc; D3DX11_EFFECT_SHADER_DESC shaderDesc; effectPass->GetVertexShaderDesc( &passDesc ); passDesc.pShaderVariable ->GetShaderDesc( passDesc.ShaderIndex , &shaderDesc ); d3dResult = d3dDevice_ ->CreateInputLayout( solidColorLayout , totalLayoutElements , shaderDesc.pBytecode , shaderDesc.BytecodeLength , &inputLayout_ ); buffer ->Release(); if( FAILED( d3dResult )) { DXTRACE_MSG( "´´½¨ÊäÈë²ãʧ°Ü£¡" ); return false; } VertexPos vertices[ ] = { { XMFLOAT3( -1.0f , 1.0f , -1.0f ) , XMFLOAT2( 0.0f , 0.0f ) } , { XMFLOAT3( 1.0f , 1.0f , -1.0f ) , XMFLOAT2( 1.0f , 0.0f ) } , { XMFLOAT3( 1.0f , 1.0f , 1.0f ) , XMFLOAT2( 1.0f , 1.0f ) } , { XMFLOAT3( -1.0f , 1.0f , 1.0f ) , XMFLOAT2( 0.0f , 1.0f ) } , { XMFLOAT3( -1.0f , -1.0f , -1.0f ) , XMFLOAT2( 0.0f , 0.0f ) } , { XMFLOAT3( 1.0f , -1.0f , -1.0f ) , XMFLOAT2( 1.0f , 0.0f ) } , { XMFLOAT3( 1.0f , -1.0f , 1.0f ) , XMFLOAT2( 1.0f , 1.0f ) } , { XMFLOAT3( -1.0f , -1.0f , 1.0f ) , XMFLOAT2( 0.0f , 1.0f ) } , { XMFLOAT3( -1.0f , -1.0f , 1.0f ) , XMFLOAT2( 0.0f , 0.0f ) } , { XMFLOAT3( -1.0f , -1.0f , -1.0f ) , XMFLOAT2( 1.0f , 0.0f ) } , { XMFLOAT3( -1.0f , 1.0f , -1.0f ) , XMFLOAT2( 1.0f , 1.0f ) } , { XMFLOAT3( -1.0f , 1.0f , 1.0f ) , XMFLOAT2( 0.0f , 1.0f ) } , { XMFLOAT3( 1.0f , -1.0f , 1.0f ) , XMFLOAT2( 0.0f , 0.0f ) } , { XMFLOAT3( 1.0f , -1.0f , -1.0f ) , XMFLOAT2( 1.0f , 0.0f ) } , { XMFLOAT3( 1.0f , 1.0f , -1.0f ) , XMFLOAT2( 1.0f , 1.0f ) } , { XMFLOAT3( 1.0f , 1.0f , 1.0f ) , XMFLOAT2( 0.0f , 1.0f ) } , { XMFLOAT3( -1.0f , -1.0f , -1.0f ) , XMFLOAT2( 0.0f , 0.0f ) } , { XMFLOAT3( 1.0f , -1.0f , -1.0f ) , XMFLOAT2( 1.0f , 0.0f ) } , { XMFLOAT3( 1.0f , 1.0f , -1.0f ) , XMFLOAT2( 1.0f , 1.0f ) } , { XMFLOAT3( -1.0f , 1.0f , -1.0f ) , XMFLOAT2( 0.0f , 1.0f ) } , { XMFLOAT3( -1.0f , -1.0f , 1.0f ) , XMFLOAT2( 0.0f , 0.0f ) } , { XMFLOAT3( 1.0f , -1.0f , 1.0f ) , XMFLOAT2( 1.0f , 0.0f ) } , { XMFLOAT3( 1.0f , 1.0f , 1.0f ) , XMFLOAT2( 1.0f , 1.0f ) } , { XMFLOAT3( -1.0f , 1.0f , 1.0f ) , XMFLOAT2( 0.0f , 1.0f ) } }; D3D11_BUFFER_DESC vertexDesc; ZeroMemory( &vertexDesc , sizeof( vertexDesc )); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof( VertexPos ) * 24; D3D11_SUBRESOURCE_DATA resourceData; ZeroMemory( &resourceData , sizeof( resourceData )); resourceData.pSysMem = vertices; d3dResult = d3dDevice_ ->CreateBuffer( &vertexDesc , &resourceData , &vertexBuffer_ ); if( FAILED( d3dResult )) { DXTRACE_MSG( "´´½¨¶¥µã»º³åÇøʧ°Ü£¡" ); return false; } WORD indices[ ] = { 3 , 1 , 0 , 2 , 1 , 3 , 6 , 4 , 5 , 7 , 4 , 6 , 11 , 9 , 8 , 10 , 9 , 11 , 14 , 12 , 13 , 15 , 12 , 14 , 19 , 17 , 16 , 18 , 17 , 19 , 22 , 20 , 21 ,23 , 20 , 22 }; D3D11_BUFFER_DESC indexDesc; ZeroMemory( &indexDesc , sizeof( indexDesc )); indexDesc.Usage = D3D11_USAGE_DEFAULT ; indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexDesc.ByteWidth = sizeof( WORD ) * 36 ; indexDesc.CPUAccessFlags = 0; resourceData.pSysMem = indices; d3dResult =d3dDevice_ ->CreateBuffer( &indexDesc , &resourceData , &indexBuffer_ ); if( FAILED( d3dResult )) { DXTRACE_MSG( "´´½¨Ë÷Òý»º³åÇøʧ°Ü£¡" ); return false; } d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_ , "decal.dds" , 0 , 0 , &colorMap_ , 0 ); if( FAILED( d3dResult )) { DXTRACE_MSG( "¼ÓÔØÎÆÀíͼÏñʧ°Ü£¡" ); return false; } D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory( &colorMapDesc , sizeof( colorMapDesc )); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; d3dResult = d3dDevice_ ->CreateSamplerState( &colorMapDesc ,&colorMapSampler_ ); if( FAILED( d3dResult )) { DXTRACE_MSG( "´´½¨²ÉÑùÆ÷ʧ°Ü£¡" ); return false; } viewMatrix_ = XMMatrixIdentity(); projMatrix_ = XMMatrixPerspectiveFovLH( XM_PIDIV4 , 800.0f / 600.0f , 0.01f , 100.0f ); return true; }
bool FontManager::LoadContent( ) { ID3DBlob* vsBuffer = 0; // compile the vertex shader from fx file bool compileResult = game_->CompileD3DShader( "TextureMap_Font.fx", "VS_Main", "vs_4_0", &vsBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling the vertex shader!" ); return false; } HRESULT d3dResult; // create the vertex shader d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), 0, &solidColorVS_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the vertex shader!" ); if( vsBuffer ) vsBuffer->Release( ); return false; } D3D11_INPUT_ELEMENT_DESC solidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout ); // create the input layout d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ ); vsBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the input layout!" ); return false; } ID3DBlob* psBuffer = 0; // compile the pixel shader from fx file compileResult = game_->CompileD3DShader( "TextureMap_Font.fx", "PS_Main", "ps_4_0", &psBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling pixel shader!" ); return false; } // create the pixel shader d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ), psBuffer->GetBufferSize( ), 0, &solidColorPS_ ); psBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating pixel shader!" ); return false; } // load the texture image d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "Assets/Images/Font.png", 0, 0, &colorMap_, 0 ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to load the texture image!" ); return false; } D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) ); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; // create the sampler state d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc, &colorMapSampler_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create color map sampler state!" ); return false; } D3D11_BUFFER_DESC vertexDesc; ZeroMemory( &vertexDesc, sizeof( vertexDesc ) ); vertexDesc.Usage = D3D11_USAGE_DYNAMIC; vertexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; const int sizeOfSprite = sizeof( VertexPos ) * 6; const int maxLetters = 24; vertexDesc.ByteWidth = sizeOfSprite * maxLetters; // create the vertex buffer d3dResult = d3dDevice_->CreateBuffer( &vertexDesc, 0, &vertexBuffer_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create vertex buffer!" ); return false; } return true; }
AaModelInfo* AaBinaryModelLoader::load(std::string filename) { AaModelSerialized* m; std::ifstream ifs(filename, std::ios::binary); if(ifs.fail()) { AaLogger::getLogger()->writeMessage("ERROR Failed to open file "+filename); return NULL; } { boost::archive::binary_iarchive ia(ifs); ia >> m; } RawModelInfo* rawModel = new RawModelInfo; rawModel->vertices = new float[m->vertex_count*3]; rawModel->vertex_count = m->vertex_count; VertexPos* vertices = new VertexPos[m->vertex_count]; VertexPos2* vertices2 = new VertexPos2[m->vertex_count]; for( int i = 0; i < m->vertex_count; i++ ) { vertices[i].pos = XMFLOAT3( m->positions_[i*3], m->positions_[i*3 + 1], m->positions_[i*3 + 2] ); vertices[i].tex0 = XMFLOAT2( m->texCoords_[i*2] , m->texCoords_[i*2 + 1] ); vertices2[i].norm = XMFLOAT3( m->normals_[i*3], m->normals_[i*3 + 1], m->normals_[i*3 + 2] ); vertices2[i].tang = XMFLOAT3( m->tangents_[i*3], m->tangents_[i*3 + 1], m->tangents_[i*3 + 2] ); rawModel->vertices[i*3] = m->positions_[i*3]; rawModel->vertices[i*3+1] = m->positions_[i*3+1]; rawModel->vertices[i*3+2] = m->positions_[i*3+2]; } if(m->useindices) { rawModel->indices = new WORD[m->index_count]; for( int i = 0; i < m->index_count; i++ ) { rawModel->indices[i] = m->indices_[i]; } rawModel->index_count = m->index_count; } else { rawModel->index_count = 0; } AaModelInfo* model= new AaModelInfo(); model->rawInfo = rawModel; D3D11_BUFFER_DESC indexDesc; ZeroMemory( &indexDesc, sizeof( indexDesc ) ); indexDesc.Usage = D3D11_USAGE_DEFAULT; indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexDesc.ByteWidth = sizeof( WORD ) * m->index_count; indexDesc.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA resourceData; ZeroMemory( &resourceData, sizeof( resourceData ) ); resourceData.pSysMem = m->indices_; HRESULT d3dResult = d3dDevice->CreateBuffer( &indexDesc, &resourceData, &model->indexBuffer_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create index buffer!" ); return NULL; } D3D11_BUFFER_DESC vertexDesc; ZeroMemory( &vertexDesc, sizeof( vertexDesc ) ); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof( VertexPos ) * m->vertex_count; ZeroMemory( &resourceData, sizeof( resourceData ) ); resourceData.pSysMem = vertices; d3dResult = d3dDevice->CreateBuffer( &vertexDesc, &resourceData, &model->vertexBuffers_[0] ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create vertex buffer!" ); return false; } ZeroMemory( &vertexDesc, sizeof( vertexDesc ) ); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof( VertexPos2 ) * m->vertex_count; ZeroMemory( &resourceData, sizeof( resourceData ) ); resourceData.pSysMem = vertices2; d3dResult = d3dDevice->CreateBuffer( &vertexDesc, &resourceData, &model->vertexBuffers_[1] ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create vertex buffer!" ); return false; } //input do vertex shadera D3D11_INPUT_ELEMENT_DESC vLp= { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; D3D11_INPUT_ELEMENT_DESC vLtc = { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }; D3D11_INPUT_ELEMENT_DESC vLn = { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; D3D11_INPUT_ELEMENT_DESC vLt = { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }; model->vertexLayout = new D3D11_INPUT_ELEMENT_DESC[4]; model->vertexLayout[0] = vLp; model->vertexLayout[1] = vLtc; model->vertexLayout[2] = vLn; model->vertexLayout[3] = vLt; model->totalLayoutElements = 4; model->vBuffersCount = 2; model->usesIndexBuffer=true; model->vertexCount=m->index_count; delete m; delete [] vertices; delete [] vertices2; return model; }
bool Comet::LoadContent( ) { ID3DBlob* vsBuffer = 0; // compile the vertex shader from fx file bool compileResult = game_->CompileD3DShader( "TextureMap_Sprites.fx", "VS_Main", "vs_4_0", &vsBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling the vertex shader!" ); return false; } HRESULT d3dResult; // create the vertex shader d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), 0, &solidColorVS_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the vertex shader!" ); if( vsBuffer ) vsBuffer->Release( ); return false; } D3D11_INPUT_ELEMENT_DESC solidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout ); // create the input layout d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ ); vsBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the input layout!" ); return false; } ID3DBlob* psBuffer = 0; // compile the pixel shader from fx file compileResult = game_->CompileD3DShader( "TextureMap_Sprites.fx", "PS_Main", "ps_4_0", &psBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling pixel shader!" ); return false; } // create the pixel shader d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ), psBuffer->GetBufferSize( ), 0, &solidColorPS_ ); psBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating pixel shader!" ); return false; } // load the texture image d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "Assets/Images/Comet.png", 0, 0, &colorMap_, 0 ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to load the texture image!" ); return false; } D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) ); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; // create the sampler state d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc, &colorMapSampler_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create color map sampler state!" ); return false; } ID3D11Resource* colorTex; colorMap_->GetResource( &colorTex ); D3D11_TEXTURE2D_DESC colorTexDesc; ( ( ID3D11Texture2D* )colorTex )->GetDesc( &colorTexDesc ); colorTex->Release( ); float halfWidth = ( float )colorTexDesc.Width / 2.0f; float halfHeight = ( float )colorTexDesc.Height / 2.0f; D3D11_BUFFER_DESC vertexDesc; ZeroMemory( &vertexDesc, sizeof( vertexDesc ) ); vertexDesc.Usage = D3D11_USAGE_DYNAMIC; vertexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof( VertexPos ) * 4; // create the vertex buffer d3dResult = d3dDevice_->CreateBuffer( &vertexDesc, 0, &vertexBuffer_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create vertex buffer!" ); return false; } D3D11_BUFFER_DESC constDesc; ZeroMemory( &constDesc, sizeof( constDesc ) ); constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constDesc.ByteWidth = sizeof( XMMATRIX ); constDesc.Usage = D3D11_USAGE_DEFAULT; // create the constant buffer d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &mvpCB_ ); if( FAILED( d3dResult ) ) { return false; } // load the sprite sheet with sprite names and coordinates spriteSheet_ = new SpriteSheet( game_, 4, 1, ( float )colorTexDesc.Width, ( float )colorTexDesc.Height ); spriteWidth_ = spriteSheet_->GetSheetWidth( ) / spriteSheet_->GetHorizontalSprites( ); spriteHeight_ = spriteSheet_->GetSheetHeight( ) / spriteSheet_->GetVerticalSprites( ); // add coordinates to animations vector<XMFLOAT2> walking; walking.push_back( XMFLOAT2( 0.0f, 0.0f ) ); walking.push_back( XMFLOAT2( 1.0f, 0.0f ) ); walking.push_back( XMFLOAT2( 2.0f, 0.0f ) ); walking.push_back( XMFLOAT2( 3.0f, 0.0f ) ); spriteSheet_->AddAnimationToMap( "walking" , walking, 0.095f ); // create template of collision box float spriteHalfWidth = spriteWidth_ / 2.0f; float spriteHalfHeight = spriteHeight_ / 2.0f; XMFLOAT3 pts[] = { XMFLOAT3( -(spriteHalfWidth/ 2.5f), -(spriteHalfHeight/2.0f), 1.0f ), XMFLOAT3( ( spriteHalfWidth / 6.0f ), -( spriteHalfHeight / 2.0f ), 1.0f ), XMFLOAT3( (spriteHalfWidth/ 6.0f), -spriteHalfHeight, 1.0f ), XMFLOAT3( -( spriteHalfWidth / 2.5f ), -spriteHalfHeight, 1.0f ), XMFLOAT3( -(spriteHalfWidth/ 2.5f), -(spriteHalfHeight/2.0f), 1.0f ), }; for( int i = 0; i < 5; i++ ) { collisionTemplate_.push_back( pts[i] ); } Initialize( ); return true; }
// uses concept of getting parsable tokens seperated by whitespace and '/' // one line of file is parsed at a time, lines seperated by '\n' void ObjFileModel::parsefile() { tokenptr=0; // token pointer points to first element of buffer int tokenstart, tokenlength; xyz tempxyz; xy tempxy; bool success; int line=0; do { line++; // keep track of current line number for error reporting if(!getnexttoken(tokenstart, tokenlength)) continue; // get first token on line, go to next line if first token is \n // ADD FURTHER KEYWORDS HERE TO EXTEND CAPABILITIES if(strncmp(&fbuffer[tokenstart], "v ", 2)==0) // VERTEX POSITION - note the space in the string is needed (see vt, etc) { success=true; // used to see if correct number of tokens left on line for this type of attribute success = success && getnexttoken(tokenstart, tokenlength); tempxyz.x = (float) atof(&fbuffer[tokenstart]); success = success && getnexttoken(tokenstart, tokenlength); tempxyz.y = (float) atof(&fbuffer[tokenstart]); success = success && getnexttoken(tokenstart, tokenlength); tempxyz.z = (float) atof(&fbuffer[tokenstart]); // if not correct number of tokens, display error in debug output if(!success) {char s[100] = "ERROR: Badly formatted vertex, line : "; _itoa(line, &s[strlen(s)], 10); strcat(s, " : "); strcat(s, filename.c_str()); DXTRACE_MSG(s); } position_list.push_back(tempxyz); // add a new element to the list } else if(strncmp(&fbuffer[tokenstart], "vt", 2)==0) // TEXTURE COORDINATES { success=true; success = success && getnexttoken(tokenstart, tokenlength); tempxy.x = (float) atof(&fbuffer[tokenstart]); success = success && getnexttoken(tokenstart, tokenlength); tempxy.y = (float) atof(&fbuffer[tokenstart]); if(!success) {char s[100] = "ERROR: Badly formatted texture coordinate, line : "; _itoa(line, &s[strlen(s)], 10); strcat(s, " : "); strcat(s, filename.c_str()); DXTRACE_MSG(s); } texcoord_list.push_back(tempxy); } else if(strncmp(&fbuffer[tokenstart], "vn", 2)==0) // NORMALS { success=true; success = success && getnexttoken(tokenstart, tokenlength); tempxyz.x = (float) atof(&fbuffer[tokenstart]); success = success && getnexttoken(tokenstart, tokenlength); tempxyz.y = (float) atof(&fbuffer[tokenstart]); success = success && getnexttoken(tokenstart, tokenlength); tempxyz.z = (float) atof(&fbuffer[tokenstart]); if(!success) {char s[100] = "ERROR: Badly formatted normal, line : "; _itoa(line, &s[strlen(s)], 10); strcat(s, " : "); strcat(s, filename.c_str()); DXTRACE_MSG(s); } normal_list.push_back(tempxyz); } else if(strncmp(&fbuffer[tokenstart], "f ", 2)==0) // FACE - only deals with triangles so far { int tempptr = tokenstart + 2; // skip "f " int forwardslashcount=0; bool adjacentslash = false; // this works out how many elements are specified for a face, e.g. // f 1 2 3 -> 0 forward slashes = just position // f 1/1 2/2 3/3 -> 3 slashes = position and texcoords // f 1/1/1 2/2/2 3/3/3 -> 6 slashes = position, texcoords, normals // f 1//1 2//2 3//3 -> 6 slashes with adjacent = position, normals while(fbuffer[tempptr] != '\n') { if(fbuffer[tempptr] == '/') { forwardslashcount++; if(fbuffer[tempptr-1] == '/') adjacentslash=true; } tempptr++; } success=true; // Get 3 sets of indices per face for(int i=0; i<3; i++) { // get vertex index success = success && getnexttoken(tokenstart, tokenlength); pindices.push_back(atoi(&fbuffer[tokenstart])); if(forwardslashcount>=3&& adjacentslash==false) // get texcoord index if required { success = success && getnexttoken(tokenstart, tokenlength); tindices.push_back(atoi(&fbuffer[tokenstart])); } if(forwardslashcount==6 || adjacentslash==true) // get normal index if required { success = success && getnexttoken(tokenstart, tokenlength); nindices.push_back(atoi(&fbuffer[tokenstart])); } } if(!success) {char s[100] = "ERROR: Badly formatted face, line : "; _itoa(line, &s[strlen(s)], 10); strcat(s, " : "); strcat(s, filename.c_str()); DXTRACE_MSG(s); } } } while(getnextline() == true); }
bool Engine::LoadContent() { // Setup our SpriteBatch. m_pSpriteBatch = new DirectX::SpriteBatch(d3dContext_); m_pFont->Initialize(d3dDevice_, std::wstring(L"Calibri18.spritefont")); m_pSprite->Initialize(d3dDevice_, std::wstring(L"Test.dds"), 10.0f, 10.0f); m_textToDisplay = Text(); m_textToDisplay.Initialize(std::wstring(L"Sarah"), DirectX::SimpleMath::Vector2(200.0f, 200.0f)); try { MSXML2::IXMLDOMDocument2Ptr xmlDoc; HRESULT hr = xmlDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60), NULL, CLSCTX_INPROC_SERVER); teamStats.InitializeTeam("Players.xml"); // Make sure the file was loaded correctly before trying to load the players. if (xmlDoc->load("Players.xml") == VARIANT_TRUE) { //xmlDoc->setProperty("SelectionLanguage", "XPath"); //teamStats.LoadPlayers(xmlDoc); } if (xmlDoc->load("input.xml") != VARIANT_TRUE) { DXTRACE_MSG("Unable to load input.xml\n"); xmlDoc->save("input.xml"); //xmlDoc-> } else { DXTRACE_MSG("XML was successfully loaded \n"); xmlDoc->setProperty("SelectionLanguage", "XPath"); MSXML2::IXMLDOMNodeListPtr wheels = xmlDoc->selectNodes("/Car/Wheels/*"); DXTRACE_MSG("Car has %u wheels\n", wheels->Getlength()); DXTRACE_MSG(wheels->Getitem(0)->text); //ptr-> MSXML2::IXMLDOMNodePtr node; node = xmlDoc->createNode(MSXML2::NODE_ELEMENT, ("Engine"), ("")); node->text = ("Engine 1.0"); xmlDoc->documentElement->appendChild(node); hr = xmlDoc->save("output.xml"); if (SUCCEEDED(hr)) { DXTRACE_MSG("output.xml successfully saved\n"); } } } catch (_com_error &e) { DXTRACE_MSG(e.ErrorMessage()); } return true; }
bool EndOfDirectX11::LoadContent() { HRESULT result = 0; ID3DBlob* buffer = 0; ID3DBlob* vsBuffer = 0; ID3DBlob* psBuffer = 0; bool compileResult = CompileD3DShader( "MultiTexture.fx", 0, "fx_5_0", &buffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling the effect shader!" ); return false; } result = D3DX11CreateEffectFromMemory( buffer->GetBufferPointer( ), buffer->GetBufferSize( ), 0, d3dDevice_, &effect_ ); if( FAILED(result) ) { DXTRACE_MSG( "error creating the effect shader" ); if( buffer ) { buffer->Release(); } return false; } buffer->Release(); D3D11_INPUT_ELEMENT_DESC solidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout ); ID3DX11EffectTechnique * colorInvTechnique = 0; colorInvTechnique = effect_->GetTechniqueByName( "MultiTexture" ); ID3DX11EffectPass * effectPass = colorInvTechnique->GetPassByIndex( 0 ); D3DX11_PASS_SHADER_DESC passDesc; D3DX11_EFFECT_SHADER_DESC shaderDesc; effectPass->GetVertexShaderDesc( &passDesc ); passDesc.pShaderVariable->GetShaderDesc( passDesc.ShaderIndex, &shaderDesc ); result = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements, shaderDesc.pBytecode, shaderDesc.BytecodeLength, &inputLayout_ ); if( FAILED( result ) ) { DXTRACE_MSG( "Error creating the input layout" ); return false; } VertexPos vertices[] = { { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, }; D3D11_BUFFER_DESC vertexDesc; ZeroMemory( &vertexDesc, sizeof( vertexDesc ) ); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof( VertexPos ) * 24; D3D11_SUBRESOURCE_DATA resourceData; ZeroMemory( &resourceData, sizeof( resourceData ) ); resourceData.pSysMem = vertices; result = d3dDevice_->CreateBuffer( &vertexDesc, &resourceData, &vertexBuffer_ ); if( FAILED( result ) ) { DXTRACE_MSG( "Failed to create vertex buffer!" ); return false; } WORD indices[] = { 3, 1, 0, 2, 1, 3, 6, 4, 5, 7, 4, 6, 11, 9, 8, 10, 9, 11, 14, 12, 13, 15, 12, 14, 19, 17, 16, 18, 17, 19, 22, 20, 21, 23, 20, 22 }; D3D11_BUFFER_DESC indexDesc; ZeroMemory( &indexDesc, sizeof( indexDesc ) ); indexDesc.Usage = D3D11_USAGE_DEFAULT; indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexDesc.ByteWidth = sizeof( WORD ) * 36; indexDesc.CPUAccessFlags = 0; resourceData.pSysMem = indices; result = d3dDevice_->CreateBuffer( &indexDesc, &resourceData, &indexBuffer_ ); if( FAILED( result ) ) { DXTRACE_MSG( "Error in creating index buffer" ); return false; } result = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "decal.dds", 0, 0, &colorMap_, 0 ); if( FAILED( result ) ) { DXTRACE_MSG( "Error in creating ShaderResource by decal.dds" ); return false; } result = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "decal2.dds", 0, 0, &secondMap_, 0 ); if( FAILED( result ) ) { DXTRACE_MSG( "Error in creating shader resource by decal2.dds" ); return false; } D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) ); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; result = d3dDevice_->CreateSamplerState( &colorMapDesc, &samplerState_ ); if( FAILED(result) ) { return false; } D3D11_BUFFER_DESC constDesc; ZeroMemory( &constDesc, sizeof( constDesc ) ); constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constDesc.ByteWidth = sizeof( XMMATRIX ); constDesc.Usage = D3D11_USAGE_DEFAULT; result = d3dDevice_->CreateBuffer( &constDesc, 0, &worldCB_ ); if( FAILED( result ) ) { DXTRACE_MSG( "Error in creating world constant buffer" ); return false; } result = d3dDevice_->CreateBuffer( &constDesc, 0, &viewCB_ ); if( FAILED( result ) ) { DXTRACE_MSG( "Error in creating view constant buffer" ); return false; } result = d3dDevice_->CreateBuffer( &constDesc, 0, &projCB_ ); if( FAILED( result ) ) { DXTRACE_MSG( "Error in creating project constant buffer" ); return false; } viewMatrix_ = XMMatrixIdentity(); projMatrix_ = XMMatrixPerspectiveFovLH( XM_PIDIV4, 800.0f / 600.0f, 0.01f, 100.0f ); XMMATRIX rotationMat = XMMatrixRotationY( XM_PIDIV4 * 0.5 ); XMMATRIX translationMat = XMMatrixTranslation( 0.0f, 0.0f, 6.0f ); worldMat_ = rotationMat * translationMat; return true; }
bool ModelsDemo::LoadContent( ) { //////////////////////////////GRID STUFF/////////////////////// MyGrid = new WorldGrid(120,120); //MyGrid->InitSnow(); //MyGrid->BuildBuffer(d3dDevice_, 26.0f, 20.0f); //26 20 ID3DBlob* vsBuffer = 0; ////////shaders start bool compileResult = CompileD3DShader( "TextureMap.fx", "VS_Main", "vs_4_0", &vsBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling the vertex shader!" ); return false; } HRESULT d3dResult; d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), 0, &textureMapVS_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the vertex shader!" ); if( vsBuffer ) vsBuffer->Release( ); return false; } D3D11_INPUT_ELEMENT_DESC solidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "BITANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 44, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout ); d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ ); //vsBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the input layout!" ); return false; } ID3DBlob* psBuffer = 0; compileResult = CompileD3DShader( "TextureMap.fx", "PS_Main", "ps_4_0", &psBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling pixel shader!" ); return false; } d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ), psBuffer->GetBufferSize( ), 0, &textureMapPS_ ); //psBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating pixel shader!" ); return false; } //////////////////////////////////////////////////////////////////normal shaders ////////shaders start compileResult = CompileD3DShader( "NormalMap.fx", "VS_Main", "vs_4_0", &vsBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling the vertex shader!" ); return false; } d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), 0, &normalTextureMapVS_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the vertex shader!" ); if( vsBuffer ) vsBuffer->Release( ); return false; } d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ ); //vsBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the input layout!" ); return false; } compileResult = CompileD3DShader( "NormalMap.fx", "PS_Main", "ps_4_0", &psBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling pixel shader!" ); return false; } d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ), psBuffer->GetBufferSize( ), 0, &normalTextureMapPS_ ); //psBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating pixel shader!" ); return false; } ////////////////////////////////////////////text 2d shaders//////////////////////////////////////////////////////////// //ID3DBlob* vsBuffer = 0; vsBuffer = 0; compileResult = CompileD3DShader( "TextTextureMap.fx", "VS_Main", "vs_4_0", &vsBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling the vertex shader!" ); return false; } d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), 0, &textTextureMapVS_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the vertex shader!" ); if( vsBuffer ) vsBuffer->Release( ); return false; } D3D11_INPUT_ELEMENT_DESC textSolidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; totalLayoutElements = ARRAYSIZE( textSolidColorLayout ); d3dResult = d3dDevice_->CreateInputLayout( textSolidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &textInputLayout_ ); vsBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the input layout!" ); return false; } //ID3DBlob* psBuffer = 0; psBuffer = 0; compileResult = CompileD3DShader( "TextTextureMap.fx", "PS_Main", "ps_4_0", &psBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling pixel shader!" ); return false; } d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ), psBuffer->GetBufferSize( ), 0, &textTextureMapPS_ ); psBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating pixel shader!" ); return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////texture d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "fontEX.png", 0, 0, &textColorMap_, 0 ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to load the texture image!" ); return false; } /////////////////// d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "tilemaptemplate.png", 0, 0, &GridColorMap_, 0 ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to load the texture image!" ); return false; } d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "tilemaplava.png", 0, 0, &GridColorMapLava_, 0 ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to load the texture image!" ); return false; } d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "tilemaptemple.png", 0, 0, &GridColorMapTemple_, 0 ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to load the texture image!" ); return false; } /////////////////// D3D11_SAMPLER_DESC textColorMapDesc; ZeroMemory( &textColorMapDesc, sizeof( textColorMapDesc ) ); textColorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; textColorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; textColorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; textColorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; textColorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; textColorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; d3dResult = d3dDevice_->CreateSamplerState( &textColorMapDesc, &textColorMapSampler_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create color map sampler state!" ); return false; } D3D11_BUFFER_DESC textVertexDesc; ZeroMemory( &textVertexDesc, sizeof( textVertexDesc ) ); textVertexDesc.Usage = D3D11_USAGE_DYNAMIC; textVertexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; textVertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; const int sizeOfSprite = sizeof( TextVertexPos ) * 6; const int maxLetters = 24; textVertexDesc.ByteWidth = sizeOfSprite * maxLetters; d3dResult = d3dDevice_->CreateBuffer( &textVertexDesc, 0, &textVertexBuffer_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create vertex buffer!" ); return false; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "Image/decal.dds", 0, 0, &colorMap_, 0 ); //"41.jpg", 0, 0, &colorMap_, 0 ); //TEXTURE_NAME, 0, 0, &colorMap_, 0 ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to load the texture image!" ); return false; } D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) ); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; //colorMapDesc.Filter = D3D11_FILTER_ANISOTROPIC; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc, &colorMapSampler_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create color map sampler state!" ); return false; } D3D11_BUFFER_DESC constDesc; ZeroMemory( &constDesc, sizeof( constDesc ) ); constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constDesc.ByteWidth = sizeof( XMMATRIX ); constDesc.Usage = D3D11_USAGE_DEFAULT; d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &viewCB_ ); if( FAILED( d3dResult ) ) { return false; } d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &projCB_ ); if( FAILED( d3dResult ) ) { return false; } d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &worldCB_ ); if( FAILED( d3dResult ) ) { return false; } constDesc.ByteWidth = sizeof( XMFLOAT4 ); d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &camPosCB_ ); if( FAILED( d3dResult ) ) { return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////// /* D3D11_BLEND_DESC blendDesc2; ZeroMemory( &blendDesc2, sizeof( blendDesc2 ) ); blendDesc2.RenderTarget[0].BlendEnable = TRUE; blendDesc2.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc2.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc2.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendDesc2.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc2.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; blendDesc2.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendDesc2.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; d3dDevice_->CreateBlendState( &blendDesc2, &alphaBlendState_ ); //d3dDevice_->CreateBlendState( &BlendState, &alphaBlendState_ ); d3dContext_->OMSetBlendState( alphaBlendState_, blendFactor, 0xFFFFFFFF );*/ ////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D11_BLEND_DESC blendStateDescription; // Clear the blend state description. ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC)); // Create an alpha enabled blend state description. blendStateDescription.RenderTarget[0].BlendEnable = TRUE; //blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; //blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f; // Create the blend state using the description. d3dResult = d3dDevice_->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState); if(FAILED(d3dResult)) { return false; } // Modify the description to create an alpha disabled blend state description. blendStateDescription.RenderTarget[0].BlendEnable = FALSE; // Create the blend state using the description. d3dResult = d3dDevice_->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState); if(FAILED(d3dResult)) { return false; } projMatrix_ = XMMatrixPerspectiveFovLH( XM_PIDIV4, 800.0f / 600.0f, 0.01f, 10000.0f ); projMatrix_ = XMMatrixTranspose( projMatrix_ ); camera_.SetDistance( 12.0f, 4.0f, 20.0f ); return true; }
//初始化 bool Dx11DemoBase::Initialize( HINSTANCE hInstance , HWND hwnd ) { hInstance_ = hInstance; hwnd_ = hwnd; RECT dimensions;//创建矩形对象 //获取窗口客户区 GetClientRect( hwnd , &dimensions ); unsigned int width = dimensions.right - dimensions.left; unsigned int height = dimensions.bottom - dimensions.top; D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE }; unsigned int totalDriverTypes = ARRAYSIZE( driverTypes ); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; unsigned int totalFeatureLevels = ARRAYSIZE( featureLevels ); DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory( &swapChainDesc , sizeof( swapChainDesc )); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;//specfic the Format swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; swapChainDesc.Windowed = true; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; unsigned int creationFlags = 0; //Create the DirectX 11 device,context,swapchain #ifdef _DEBUG creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT result; unsigned int driver = 0 ; for( driver = 0; driver < totalDriverTypes; ++driver ) { result = D3D11CreateDeviceAndSwapChain( 0, driverTypes[driver], 0, creationFlags, featureLevels, totalFeatureLevels, D3D11_SDK_VERSION, &swapChainDesc, &swapChain_, &d3dDevice_, &featureLevel_, &d3dContext_ ); if( SUCCEEDED( result ) ) { driverType_ = driverTypes[ driver ]; break; } } if( FAILED( result )) { DXTRACE_MSG( "Failed to create the Direct3D device!" ); return false; } //Render TargetView Creation ID3D11Texture2D * backBufferTexture; result = swapChain_->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID * )&backBufferTexture ); if( FAILED( result ) ) { DXTRACE_MSG( "Failed to get the swap chain back buffer!" ); return false; } result = d3dDevice_->CreateRenderTargetView( backBufferTexture, 0, &backBufferTarget_ ); if( backBufferTexture ) { backBufferTexture->Release(); } if( FAILED ( result )) { DXTRACE_MSG( "Failed to create the render target view! "); return false; } d3dContext_->OMSetRenderTargets( 1, &backBufferTarget_, 0 ); //The creation and setting of a full-screen viewport D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>( width ); viewport.Height = static_cast<float>( height ); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; d3dContext_->RSSetViewports( 1, &viewport ); ZeroMemory( keyboardKeys_ , sizeof( keyboardKeys_ )); ZeroMemory( prevKeyboardKeys_ , sizeof( prevKeyboardKeys_ )); result = DirectInput8Create( hInstance_ , DIRECTINPUT_VERSION , IID_IDirectInput8 , ( void ** ) & directInput_ , 0 ); if( FAILED( result )) { return false; } result = directInput_ ->CreateDevice( GUID_SysKeyboard , &keyboardDevice_ , 0 ); if( FAILED( result )) { return false; } result = keyboardDevice_ ->SetDataFormat( &c_dfDIKeyboard ); if( FAILED( result )) { return false; } result = keyboardDevice_ ->SetCooperativeLevel( hwnd_ , DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); if( FAILED( result )) { return false; } result = keyboardDevice_ ->Acquire(); if( FAILED( result )) { return false; } mousePosX_ = mousePosY_ = mouseWheel_ = 0 ; result = directInput_ ->CreateDevice( GUID_SysMouse , &mouseDevice_ , 0 ); if( FAILED( result )) { return false; } result = mouseDevice_ ->SetDataFormat( &c_dfDIMouse ); if( FAILED( result )) { return false; } result = mouseDevice_ ->SetCooperativeLevel( hwnd_ , DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); if( FAILED( result )) { return false; } result = mouseDevice_ ->Acquire(); if( FAILED( result )) { return false; } return LoadContent(); }
bool ModelsDemo::DrawString( char* message, float startX, float startY ) { //float clearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; //d3dContext_->ClearRenderTargetView( backBufferTarget_, clearColor ); // Size in bytes for a single sprite. const int sizeOfSprite = sizeof( TextVertexPos ) * 6; // Demo's dynamic buffer setup for max of 24 letters. const int maxLetters = 24; int length = strlen( message ); // Clamp for strings too long. if( length > maxLetters ) length = maxLetters; // Char's width on screen. float charWidth = 32.0f / 800.0f; // Char's height on screen. float charHeight = 32.0f / 640.0f; // Char's texel width. //float texelWidth = 32.0f / 864.0f; float texelWidth = 32.0f / 3072.0f; // verts per-triangle (3) * total triangles (2) = 6. const int verticesPerLetter = 6; D3D11_MAPPED_SUBRESOURCE mapResource; HRESULT d3dResult = d3dContext_->Map( textVertexBuffer_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapResource ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to map resource!" ); return false; } // Point to our vertex buffer's internal data. TextVertexPos *spritePtr = ( TextVertexPos* )mapResource.pData; const int indexSpace = static_cast<char>( ' ' ); const int indexA = static_cast<char>( 'A' ); const int indexZ = static_cast<char>( 'Z' ); const int indexSquare = static_cast<char>( 127 ); for( int i = 0; i < length; ++i ) { float thisStartX = startX + ( charWidth * static_cast<float>( i ) ); float thisEndX = thisStartX + charWidth; float thisEndY = startY + charHeight; spritePtr[0].pos = XMFLOAT3( thisEndX, thisEndY, 1.0f ); spritePtr[1].pos = XMFLOAT3( thisEndX, startY, 1.0f ); spritePtr[2].pos = XMFLOAT3( thisStartX, startY, 1.0f ); spritePtr[3].pos = XMFLOAT3( thisStartX, startY, 1.0f ); spritePtr[4].pos = XMFLOAT3( thisStartX, thisEndY, 1.0f ); spritePtr[5].pos = XMFLOAT3( thisEndX, thisEndY, 1.0f ); int texLookup = 0; int letter = static_cast<char>( message[i] ); //if( letter < indexA || letter > indexZ ) if( letter < indexSpace || letter > indexSquare ) { // Grab one index past Z, which is a blank space in the texture. // texLookup = ( indexZ - indexA ) + 1; texLookup = indexSquare; } else { // A = 0, B = 1, Z = 25, etc. //texLookup = ( letter - indexA ); texLookup = ( letter - indexSpace ); } float tuStart = 0.0f + ( texelWidth * static_cast<float>( texLookup ) ); float tuEnd = tuStart + texelWidth; spritePtr[0].tex0 = XMFLOAT2( tuEnd, 0.0f ); spritePtr[1].tex0 = XMFLOAT2( tuEnd, 1.0f ); spritePtr[2].tex0 = XMFLOAT2( tuStart, 1.0f ); spritePtr[3].tex0 = XMFLOAT2( tuStart, 1.0f ); spritePtr[4].tex0 = XMFLOAT2( tuStart, 0.0f ); spritePtr[5].tex0 = XMFLOAT2( tuEnd, 0.0f ); spritePtr += 6; } d3dContext_->Unmap( textVertexBuffer_, 0 ); d3dContext_->Draw( 6 * length, 0 ); return true; }
//============================================================================== bool CGraphicsMgr::Startup (HINSTANCE hInstance, HWND hwnd) { m_hInstance = hInstance; m_hWnd = hwnd; RECT dimensions; GetClientRect(hwnd, &dimensions); unsigned int width = dimensions.right - dimensions.left; unsigned int height = dimensions.bottom - dimensions.top; D3D_DRIVER_TYPE driver_types[] = { //D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE }; unsigned int driver_type_count = sizeof(driver_types) / sizeof(driver_types[0]); D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; unsigned int feature_level_count = sizeof(feature_levels) / sizeof(feature_levels[0]); DXGI_SWAP_CHAIN_DESC swap_chain_desc; SecureZeroMemory(&swap_chain_desc, sizeof(swap_chain_desc)); swap_chain_desc.BufferCount = 1; swap_chain_desc.BufferDesc.Width = width; swap_chain_desc.BufferDesc.Height = height; swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swap_chain_desc.BufferDesc.RefreshRate.Numerator = 60; swap_chain_desc.BufferDesc.RefreshRate.Denominator = 1; swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swap_chain_desc.OutputWindow = hwnd; swap_chain_desc.Windowed = true; swap_chain_desc.SampleDesc.Count = 1; swap_chain_desc.SampleDesc.Quality = 0; unsigned int creation_flags = 0; #if defined(_DEBUG) creation_flags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT hresult; unsigned int driver; for (driver = 0; driver < driver_type_count; ++driver) { hresult = D3D11CreateDeviceAndSwapChain( 0, driver_types[driver], 0, creation_flags, feature_levels, feature_level_count, D3D11_SDK_VERSION, &swap_chain_desc, &m_swapChain, &m_d3dDevice, &m_featureLevel, &m_d3dContext ); if (SUCCEEDED(hresult)) { m_driverType = driver_types[driver]; break; } } if (FAILED(hresult)) { DXTRACE_MSG(L"Failed to create the Direct3D device!"); return false; } #if defined(_DEBUG) { char tempName[] = "GraphicsMgr's SwapChain"; m_swapChain->SetPrivateData(WKPDID_D3DDebugObjectName, arrsize(tempName), tempName); } #endif // Debug layer if (SUCCEEDED(m_d3dDevice->QueryInterface(__uuidof(ID3D11Debug), (void**)&m_d3dDebug))) { ID3D11InfoQueue * d3dInfoQueue = nullptr; if (SUCCEEDED(m_d3dDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&d3dInfoQueue))) { #if defined(_DEBUG) d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true); d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true); //d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_WARNING, true); //d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_INFO, true); #endif D3D11_MESSAGE_ID hiddenMessages[] = { D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS, }; D3D11_INFO_QUEUE_FILTER filter; memset(&filter, 0, sizeof(filter)); filter.DenyList.NumIDs = _countof(hiddenMessages); filter.DenyList.pIDList = hiddenMessages; d3dInfoQueue->AddStorageFilterEntries(&filter); d3dInfoQueue->Release(); } } ID3D11Texture2D* back_buffer_texture; hresult = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&back_buffer_texture); if (FAILED(hresult)) { DXTRACE_MSG(L"Failed to get the swap chain back buffer!"); return false; } hresult = m_d3dDevice->CreateRenderTargetView(back_buffer_texture, 0, &m_backBufferTarget); if (FAILED(hresult)) { DXTRACE_MSG(L"Failed to create the render target view!"); ASSERT(!FAILED(hresult)); return false; } #if defined(_DEBUG) { char tempName[] = "GraphicsMgr's BackBufferTarget"; m_backBufferTarget->SetPrivateData(WKPDID_D3DDebugObjectName, arrsize(tempName), tempName); } #endif if (back_buffer_texture) back_buffer_texture->Release(); m_d3dContext->OMSetRenderTargets(1, &m_backBufferTarget, 0); D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>(width); viewport.Height = static_cast<float>(height); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; m_d3dContext->RSSetViewports(1, &viewport); // Don't backface cull { D3D11_RASTERIZER_DESC rasterDesc; SecureZeroMemory(&rasterDesc, sizeof(rasterDesc)); rasterDesc.CullMode = D3D11_CULL_NONE; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; //rasterDesc.FillMode = D3D11_FILL_WIREFRAME; HRESULT result = m_d3dDevice->CreateRasterizerState( &rasterDesc, &m_rasterState ); if (FAILED(result)) { ASSERT(!FAILED(result)); return false; } #if defined(_DEBUG) { char tempName[] = "GraphicsMgr's RasterState"; m_rasterState->SetPrivateData(WKPDID_D3DDebugObjectName, arrsize(tempName), tempName); } #endif m_d3dContext->RSSetState(m_rasterState); } D3D11_BUFFER_DESC const_desc; SecureZeroMemory(&const_desc, sizeof(const_desc)); const_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; const_desc.ByteWidth = sizeof(XMMATRIX); const_desc.Usage = D3D11_USAGE_DEFAULT; HRESULT d3d_result = g_graphicsMgrInt->GetDevice()->CreateBuffer(&const_desc, 0, &m_projectionFromWorldMtxCb); if (FAILED(d3d_result)) { ASSERT(!FAILED(d3d_result)); return false; } #if defined(_DEBUG) { char tempName[] = "GraphicsMgr's projectionFromWorldMtx ConstantBuffer"; m_projectionFromWorldMtxCb->SetPrivateData(WKPDID_D3DDebugObjectName, arrsize(tempName), tempName); } #endif #ifdef _DEBUG // Hacks!! Hides issues with lost pointers to VertexShaders! m_vertexShaders.reserve(16); m_pixelShaders.reserve(16); #endif ASSERT(!g_keyboardMouse); XInputKeyboardMouse * xikm = new XInputKeyboardMouse(); xikm->Startup(hInstance, hwnd, width, height); return true; }
// draws the given message on the screen bool FontManager::DrawString( char* message, float startX, float startY ) { // size in bytes for a single sprite const int sizeOfSprite = sizeof( VertexPos ) * 6; // dynamic buffer setup for max of 24 letters const int maxLetters = 24; int length = strlen( message ); // clamp for strings too long if( length > maxLetters ) length = maxLetters; // char's width on screen float charWidth = 32.0f / game_->GetScreenWidth( ); // char's height on screen float charHeight = 38.0f / game_->GetScreenHeight( ); // char's texel width float texelWidth = 32.0f / 3040.0f; // verts per-triangle (3) * total triangles (2) = 6 const int verticesPerLetter = 6; D3D11_MAPPED_SUBRESOURCE mapResource; HRESULT d3dResult = d3dContext_->Map( vertexBuffer_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapResource ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to map resource!" ); return false; } // point to our vertex buffer's internal data VertexPos *spritePtr = ( VertexPos* )mapResource.pData; const int indexFirst = static_cast<char>( ' ' ); const int indexLast = static_cast<char>( '~' ); for( int i = 0; i < length; ++i ) { float thisStartX = startX + ( charWidth * static_cast<float>( i ) ); float thisEndX = thisStartX + charWidth; float thisEndY = startY + charHeight; // set the vertex positions spritePtr[0].pos = XMFLOAT3( thisEndX, thisEndY, 1.0f ); spritePtr[1].pos = XMFLOAT3( thisEndX, startY, 1.0f ); spritePtr[2].pos = XMFLOAT3( thisStartX, startY, 1.0f ); spritePtr[3].pos = XMFLOAT3( thisStartX, startY, 1.0f ); spritePtr[4].pos = XMFLOAT3( thisStartX, thisEndY, 1.0f ); spritePtr[5].pos = XMFLOAT3( thisEndX, thisEndY, 1.0f ); int texLookup = 0; int letter = static_cast<char>( message[i] ); if( letter < indexFirst || letter > indexLast ) { // grab the first index, which is a blank space in the texture texLookup = 0; } else { // space = 0, ! = 1, ~ = 126, etc texLookup = ( letter - indexFirst ); } float tuStart = 0.0f + ( texelWidth * static_cast<float>( texLookup ) ); float tuEnd = tuStart + texelWidth; // align the texture spritePtr[0].tex0 = XMFLOAT2( tuEnd, 0.0f ); spritePtr[1].tex0 = XMFLOAT2( tuEnd, 1.0f ); spritePtr[2].tex0 = XMFLOAT2( tuStart, 1.0f ); spritePtr[3].tex0 = XMFLOAT2( tuStart, 1.0f ); spritePtr[4].tex0 = XMFLOAT2( tuStart, 0.0f ); spritePtr[5].tex0 = XMFLOAT2( tuEnd, 0.0f ); spritePtr += 6; } // unmap the buffer and draw all the vertices d3dContext_->Unmap( vertexBuffer_, 0 ); d3dContext_->Draw( 6 * length, 0 ); return true; }
ID3D11ShaderResourceView* vavImage::GetDx11Texture(ID3D11Device* dev, ID3D11DeviceContext* devc) { if (m_Image.rows == 0 || m_Image.cols == 0) { return NULL; } if (m_pTextureDraw) { m_pTextureDraw->Release(); m_pTextureDraw = 0; } if (m_pShaderResView) { m_pShaderResView->Release(); m_pShaderResView = 0; } D3D11_TEXTURE2D_DESC texDesc; ZeroMemory(&texDesc, sizeof(texDesc)); texDesc.Width = m_Image.rows; texDesc.Height = m_Image.cols; texDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; texDesc.MipLevels = 1; texDesc.ArraySize = 1; texDesc.SampleDesc.Quality = 0; texDesc.SampleDesc.Count = 1; texDesc.Usage = D3D11_USAGE_DEFAULT; texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; texDesc.CPUAccessFlags = 0; texDesc.MiscFlags = 0; D3D11_SHADER_RESOURCE_VIEW_DESC srDesc; srDesc.Format = texDesc.Format; srDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srDesc.Texture2D.MostDetailedMip = 0; srDesc.Texture2D.MipLevels = 1; float* characterImages = new float[m_Image.rows * m_Image.cols * 4]; for (int j = 0; j < m_Image.cols; ++j) { for (int i = 0; i < m_Image.rows; ++i) { int offset = (j * m_Image.rows + i) * 4; cv::Vec3b intensity = m_Image.at<cv::Vec3b>(i, j); characterImages[offset ] = intensity[2] / 255.0f; characterImages[offset + 1] = intensity[1] / 255.0f; characterImages[offset + 2] = intensity[0] / 255.0f; characterImages[offset + 3] = 1.0f; } } texDesc.Width = m_Image.rows; texDesc.Height = m_Image.cols; D3D11_SUBRESOURCE_DATA sSubData; sSubData.SysMemPitch = (UINT)(m_Image.rows * 4 * 4); sSubData.SysMemSlicePitch = (UINT)(m_Image.rows * m_Image.cols * 4 * 4); sSubData.pSysMem = characterImages; HRESULT d3dResult = dev->CreateTexture2D(&texDesc, &sSubData, &m_pTextureDraw); int x = 0; delete[] characterImages; if (FAILED(d3dResult)) { DXTRACE_MSG(L"vavImage: Failed to create texture2D!"); return 0; } d3dResult = dev->CreateShaderResourceView(m_pTextureDraw, &srDesc, &m_pShaderResView); if (FAILED(d3dResult)) { DXTRACE_MSG(L"vavImage: Failed to create ShaderResourceView!"); return 0; } return m_pShaderResView; }
bool TextureDemo::LoadContent( ) { ID3DBlob * vsBuffer = 0; bool CompileResult = CompileD3DShader( "solidGreenColor.fx" , "VS_Main" , "vs_4_0" , &vsBuffer ); if( CompileResult == false ) { MessageBox( 0 , "¼ÓÔض¥µã×ÅÉ«Æ÷ʧ°Ü£¡" , "±àÒë´íÎó£¡" , MB_OK ); return false; } HRESULT d3dResult; d3dResult = d3dDevice_ ->CreateVertexShader( vsBuffer ->GetBufferPointer() , vsBuffer ->GetBufferSize() , 0 , &solidColorVS_ ); if( FAILED( d3dResult )) { if( vsBuffer ) { vsBuffer ->Release(); } return false; } //ÓësolidGreenColor.fx¶ÔÓ¦ D3D11_INPUT_ELEMENT_DESC solidColorLayer[ ]= { { "POSITION" , 0 , DXGI_FORMAT_R32G32B32_FLOAT , 0 , 0 , D3D11_INPUT_PER_VERTEX_DATA , 0 } , { "TEXCOORD" , 1 , DXGI_FORMAT_R32G32_FLOAT , 0 , 12 , D3D11_INPUT_PER_VERTEX_DATA , 0 } }; unsigned int totalLayerElements = ARRAYSIZE( solidColorLayer ); d3dResult = d3dDevice_ ->CreateInputLayout( solidColorLayer , totalLayerElements , vsBuffer ->GetBufferPointer() , vsBuffer ->GetBufferSize() , &inputLayer_ ); vsBuffer->Release( ); ID3DBlob * psBuffer; CompileResult = CompileD3DShader( "solidGreenColor.fx" , "PS_Main" , "ps_4_0" , &psBuffer ); if( CompileResult == false ) { MessageBox( 0 , "¼ÓÔØÏñËØ×ÅÉ«Æ÷ʧ°Ü£¡" , "±àÒë´íÎó£¡" , MB_OK ); } d3dResult = d3dDevice_ ->CreatePixelShader( psBuffer ->GetBufferPointer() , psBuffer ->GetBufferSize() , 0 , &solidColorPS_ ); if( FAILED( d3dResult ) ) { return false; } VertexPos vertices[ ]= { { XMFLOAT3( 1.0f , 1.0f , 1.0f ) , XMFLOAT2( 1.0f , 1.0f )} , { XMFLOAT3( 1.0f , -1.0f , 1.0f ) , XMFLOAT2( 1.0f , 0.0f )} , { XMFLOAT3( -1.0f , -1.0f , 1.0f ) , XMFLOAT2( 0.0f , 0.0f )} , { XMFLOAT3( -1.0f , -1.0f , 1.0f ) , XMFLOAT2( 0.0f , 0.0f )} , { XMFLOAT3( -1.0f , 1.0f , 1.0f ) , XMFLOAT2( 0.0f , 1.0f )} , { XMFLOAT3( 1.0f , 1.0f , 1.0f ) , XMFLOAT2( 1.0f , 1.0f ) } , }; D3D11_BUFFER_DESC vertexDesc; ZeroMemory( &vertexDesc , sizeof( vertexDesc )); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof( VertexPos ) * 6; D3D11_SUBRESOURCE_DATA resourceData; ZeroMemory( &resourceData , sizeof( resourceData )); resourceData.pSysMem = vertices; d3dResult = d3dDevice_ ->CreateBuffer( &vertexDesc , &resourceData , &vertexBuffer_ ); if( FAILED( d3dResult )) { return false; } d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_ , "yosuga.jpg" , 0 , 0 , &colorMap_ , 0 ); if( FAILED( d3dResult )) { DXTRACE_MSG( "¼ÓÔØÎÆÀíͼÏñʧ°Ü£¡" ); return false; } D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory( &colorMapDesc , sizeof( colorMapDesc )); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; d3dResult = d3dDevice_ ->CreateSamplerState( &colorMapDesc , &colorMapSample_ ); if( FAILED( d3dResult )) { DXTRACE_MSG( "Failed to create color map sampler state!" ); return false; } return true; }
//初始化 bool Dx11DemoBase::Initialize( HINSTANCE hInstance , HWND hwnd ) { hInstance_ = hInstance; hwnd_ = hwnd; RECT dimensions;//创建矩形对象 //获取窗口客户区 GetClientRect( hwnd , &dimensions ); unsigned int width = dimensions.right - dimensions.left; unsigned int height = dimensions.bottom - dimensions.top; D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE }; unsigned int totalDriverTypes = ARRAYSIZE( driverTypes ); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; unsigned int totalFeatureLevels = ARRAYSIZE( featureLevels ); DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory( &swapChainDesc , sizeof( swapChainDesc )); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;//specfic the Format swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; swapChainDesc.Windowed = true; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; unsigned int creationFlags = 0; //Create the DirectX 11 device,context,swapchain #ifdef _DEBUG creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT result; unsigned int driver = 0 ; for( driver = 0; driver < totalDriverTypes; ++driver ) { result = D3D11CreateDeviceAndSwapChain( 0, driverTypes[driver], 0, creationFlags, featureLevels, totalFeatureLevels, D3D11_SDK_VERSION, &swapChainDesc, &swapChain_, &d3dDevice_, &featureLevel_, &d3dContext_ ); if( SUCCEEDED( result ) ) { driverType_ = driverTypes[ driver ]; break; } } if( FAILED( result )) { DXTRACE_MSG( "Failed to create the Direct3D device!" ); return false; } //Render TargetView Creation ID3D11Texture2D * backBufferTexture; result = swapChain_->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID * )&backBufferTexture ); if( FAILED( result ) ) { DXTRACE_MSG( "Failed to get the swap chain back buffer!" ); return false; } result = d3dDevice_->CreateRenderTargetView( backBufferTexture, 0, &backBufferTarget_ ); if( backBufferTexture ) { backBufferTexture->Release(); } if( FAILED ( result )) { DXTRACE_MSG( "Failed to create the render target view! "); return false; } //Create the texture2d desc D3D11_TEXTURE2D_DESC depthTexDesc; ZeroMemory( &depthTexDesc , sizeof( depthTexDesc )); depthTexDesc.Width = width; depthTexDesc.Height = height; depthTexDesc.MipLevels = 1; depthTexDesc.ArraySize = 1; depthTexDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthTexDesc.SampleDesc.Count = 1; depthTexDesc.SampleDesc.Quality = 0; depthTexDesc.Usage = D3D11_USAGE_DEFAULT; depthTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthTexDesc.CPUAccessFlags = 0; depthTexDesc.MiscFlags = 0; result = d3dDevice_ ->CreateTexture2D( &depthTexDesc , NULL , &depthTexture_ ); if( FAILED( result )) { DXTRACE_MSG( "Failed to create the depth texture!" ); return false; } //Create the depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; ZeroMemory( &descDSV , sizeof( descDSV )); descDSV.Format = depthTexDesc.Format; descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; result = d3dDevice_ ->CreateDepthStencilView( depthTexture_ , &descDSV , &depthStencilView_ ); if( FAILED( result )) { DXTRACE_MSG( "Failed to create the depth stencil view!" ); return false; } d3dContext_->OMSetRenderTargets( 1, &backBufferTarget_, depthStencilView_ ); //The creation and setting of a full-screen viewport D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>( width ); viewport.Height = static_cast<float>( height ); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; d3dContext_->RSSetViewports( 1, &viewport ); return LoadContent(); }