int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { //DX初期化にはデバイス、コンテキスト、スワップチェインの3つ、加えてレンダリングターゲット WindowDevice &window = WindowDevice::getInstance(); DX11Device &device = DX11Device::getInstance(); window.Init(hInstance, nCmdShow, TEXT("test window"), 1280, 720, true); device.Init(window.getHandle(), window.getWidth(), window.getHeight(), window.getWindowMode()); // IMGUIの初期化 ImGui_ImplDX11_Init(window.getHandle(), device.getDevice(), device.getContext()); GraphicsPipeLine deferredGPL; //=====================================================// // 頂点データ情報(FarstPass & FinalPass) 1.CreateBufferで生成 2.IASetVertexBuffersで設定 3.Drawで実行(描画) //=====================================================// //***************宣言********************// ID3D11Buffer *vertexbuffer = nullptr; // FirstPassBuffer ID3D11Buffer *finalvertexbuffer = nullptr; // FinalPassBuffer D3D11_BUFFER_DESC bd; // 生成方法(バッファー リソース) //***************頂点生成********************// // 最初描画用 (FarstPass) Vertex4UV vertex[4] = { { 100.f, 100.f, 1.0f, 1.0f, 1.0f, 0.0f }, { -100.f, 100.f, 1.0f, 1.0f, 0.0f, 0.0f }, { 100.f, -100.f, 1.0f, 1.0f, 1.0f, 1.0f }, { -100.f, -100.f, 1.0f, 1.0f, 0.0f, 1.0f }, }; // 最終描画用 (FinalPass) Vertex4UV finalvertex[4] = { { 1.f, 1.f, 1.0f, 1.0f, 1.0f, 0.0f }, { -1.f, 1.f, 1.0f, 1.0f, 0.0f, 0.0f }, { 1.f, -1.f, 1.0f, 1.0f, 1.0f, 1.0f }, { -1.f, -1.f, 1.0f, 1.0f, 0.0f, 1.0f }, }; //***************頂点バッファ設定********************//(BufferDESCに生成方法を格納&CreateBufferで生成まで) // FirstPass設定 ZeroMemory(&bd, sizeof(bd)); // 中身をゼロクリア bd.Usage = D3D11_USAGE_DYNAMIC; // バッファーで想定されている読み込みおよび書き込みの方法を識別 bd.ByteWidth = sizeof(vertex); // バッファーのサイズ(バイト単位) bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // なんのバッファですか? bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // CPUからは書き込みのみ行います device.getDevice()->CreateBuffer(&bd, nullptr, &vertexbuffer); // 設定したBufferを生成 // FinalPass設定 ZeroMemory(&bd, sizeof(bd)); // 中身をゼロクリア bd.Usage = D3D11_USAGE_DYNAMIC; // バッファーで想定されている読み込みおよび書き込みの方法を識別 bd.ByteWidth = sizeof(finalvertex); // バッファーのサイズ(バイト単位) bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // なんのバッファですか? bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // CPUからは書き込みのみ行います device.getDevice()->CreateBuffer(&bd, nullptr, &finalvertexbuffer); // 設定したBufferを生成 //***************頂点情報を格納していく********************//(BufferDESCに生成方法を格納&CreateBufferで生成まで) // FirstPass格納 D3D11_MAPPED_SUBRESOURCE ms; // Bufferを格納する為にとりあえずロックをかけないといけない。どこまでロックをかける?サブリソース データにアクセスできるようにする device.getContext()->Map(vertexbuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); // アクセス先ms memcpy(ms.pData, vertex, sizeof(vertex));// pData = vetexコピー 書き込み device.getContext()->Unmap(vertexbuffer, NULL); // ロック解除 // FinalPass格納 device.getContext()->Map(finalvertexbuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); // アクセス先ms memcpy(ms.pData, finalvertex, sizeof(finalvertex));// pData = vetexコピー 書き込み device.getContext()->Unmap(finalvertexbuffer, NULL); // ロック解除 //=====================================================// // シェーダー情報(VertexShader&PixelShader) 1.Create(Vertex & Pixel)Shaderで生成 2.(VS & PS)SetShaderで実行 //=====================================================// //***************宣言********************// ID3D11VertexShader *vs_buf = nullptr; // (first) shaderのbuffer コンパイルしたシェーダーの格納先 ID3D11PixelShader *ps_buf = nullptr; // (first) shaderのbuffer コンパイルしたシェーダーの格納先 ID3D11VertexShader *vsfinal_buf = nullptr; // (final) shaderのbuffer コンパイルしたシェーダーの格納先 ID3D11PixelShader *psfinal_buf = nullptr; // (final) shaderのbuffer コンパイルしたシェーダーの格納先 ID3D10Blob *vsblob, *psblob, *vsblobfinal, *psblobfinal; // 任意長のデータを返す際に使用 //***************シェーダーコード格納ファイルコンパイル********************// D3DX11CompileFromFile(TEXT("./Shader/VSDeferred.hlsl"), 0, 0, "main", "vs_5_0", 0, 0, 0, &vsblob, 0, 0); D3DX11CompileFromFile(TEXT("./Shader/PSDeferred.hlsl"), 0, 0, "main", "ps_5_0", 0, 0, 0, &psblob, 0, 0); D3DX11CompileFromFile(TEXT("./Shader/VSDeferredFinal.hlsl"), 0, 0, "main", "vs_5_0", 0, 0, 0, &vsblobfinal, 0, 0); D3DX11CompileFromFile(TEXT("./Shader/PSDeferredFinal.hlsl"), 0, 0, "main", "ps_5_0", 0, 0, 0, &psblobfinal, 0, 0); //***************シェーダーの設定(VS&PS)**********************************// device.getDevice()->CreateVertexShader(vsblob->GetBufferPointer(), vsblob->GetBufferSize(), nullptr, &vs_buf); // コンパイル済みシェーダーから、頂点シェーダー オブジェクトを作成 device.getDevice()->CreatePixelShader(psblob->GetBufferPointer(), psblob->GetBufferSize(), nullptr, &ps_buf); // ピクセル シェーダーを作成 device.getDevice()->CreateVertexShader(vsblobfinal->GetBufferPointer(), vsblobfinal->GetBufferSize(), nullptr, &vsfinal_buf); // コンパイル済みシェーダーから、頂点シェーダー オブジェクトを作成 device.getDevice()->CreatePixelShader(psblobfinal->GetBufferPointer(), psblobfinal->GetBufferSize(), nullptr, &psfinal_buf); // ピクセル シェーダーを作成 // 頂点シェーダーをデバイスに設定(実行) device.getContext()->VSSetShader(vsfinal_buf, nullptr, 0); // 頂点シェーダーをデバイスに設定 device.getContext()->PSSetShader(psfinal_buf, nullptr, 0); // ピクセル シェーダーをデバイスに設定 //=====================================================// /// 頂点レイアウト情報 //=====================================================// // 入力レイアウト(レイアウト情報をコンパイル済みVertexShaderから動的に構築) D3D11_INPUT_ELEMENT_DESC element[] = { // 入力アセンブラー ステージの単一の要素( HLSL セマンティクス,要素のセマンティクス インデックス,要素データのデータ型,入力アセンブラーを識別する整数値,各要素間のオフセット (バイト単位),単一の入力スロットの入力データ クラスを識別,インスタンス単位の同じデータを使用して描画するインスタンスの数) { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },// 位置情報 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 } // UV情報 }; ID3D11InputLayout *inputlayout; // 入力アセンブラー ステージの入力データにアクセス device.getDevice()->CreateInputLayout(element, ARRAYSIZE(element), vsblobfinal->GetBufferPointer(), vsblobfinal->GetBufferSize(), &inputlayout); // 格納(入力アセンブラー ステージで使用される入力バッファー データ) device.getContext()->IASetInputLayout(inputlayout); //インプットレイアウトの設定 入力アセンブラー ステージに入力レイアウト オブジェクトをバインド device.getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); // 頂点の並び方の設定(プリミティブ タイプおよびデータの順序に関する情報をバインド) // 通常描画用のパイプライン CrateDeferredPipeLine(deferredGPL); //=====================================================// // カメラ情報 //=====================================================// ConstantBuffer mtx; // Shaderに送る行列の生成 XMVECTOR hEye = XMVectorSet(0.0f, 0.0f, -2.0f, 0.0f); XMVECTOR hAt = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); XMVECTOR hUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); mtx.mView = XMMatrixLookAtLH(hEye, hAt, hUp); mtx.mWorld = XMMatrixIdentity(); mtx.mProjection = XMMatrixOrthographicLH((float) window.getWidth(), (float) window.getHeight(), 1, 5000); //=====================================================// // コンスタント情報 //=====================================================// //コンテキストバッファ:シェーダーで宣言した定数をプログラム側から変更する(主に生成、更新、シェーダーステージへのセットという3つのアクション) // constantバッファ生成 ID3D11Buffer *constantbuffer = nullptr; ZeroMemory(&bd, sizeof(bd)); // 中身をクリア // Bufferの生成方法の格納 bd.ByteWidth = sizeof(ConstantBuffer); // sizeの指定 bd.Usage = D3D11_USAGE_DEFAULT; bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; // なんのバッファですか? bd.CPUAccessFlags = 0; // CPUからは書き込みのみ行います bd.MiscFlags = 0; bd.StructureByteStride = sizeof(float); device.getDevice()->CreateBuffer(&bd, NULL, &constantbuffer); // バッファの生成 //=====================================================// // バッファ情報 //=====================================================// // テクスチャの読み込み Texture2D tex,tex2; tex.LoadFile("./Resource/Lenna.png"); tex2.LoadFile("./Resource/lenna_normal.png"); ID3D11ShaderResourceView *srv[] = { tex.getSRV(), tex2.getSRV() }; device.getContext()->PSSetShaderResources(0, 2, srv); // ピクセル シェーダー ステージにシェーダー リソースの配列をバインド // MRT(マルチレンダーターゲット) //Gバッファの生成 ジオメトリバッファ(1pass 複数描画 2次元情報として保存:頂点シェーダとピクセルシェーダの間に実行) Texture2D GBuffer[4]; UINT bindflg = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; // リソースをパイプラインにバインドする方法を識別(、バインド フラグは論理和を使って組み合わせることができる) GBuffer[0].Create(window.getWidth(), window.getHeight(), D3D11_USAGE_DEFAULT, DXGI_FORMAT_R32G32B32A32_FLOAT, bindflg); //Albed GBuffer[1].Create(window.getWidth(), window.getHeight(), D3D11_USAGE_DEFAULT, DXGI_FORMAT_R32G32B32A32_FLOAT, bindflg); //Normal GBuffer[2].Create(window.getWidth(), window.getHeight(), D3D11_USAGE_DEFAULT, DXGI_FORMAT_R32_FLOAT, bindflg); //Depth GBuffer[3].Create(window.getWidth(), window.getHeight(), D3D11_USAGE_DEFAULT, DXGI_FORMAT_R32G32B32A32_FLOAT, bindflg); //Diffuse // レンダリング時にシェーダーがアクセス可能なサブリソースを指定(ShaderResourceView) ID3D11ShaderResourceView *GBufferSRV [] = { GBuffer[0].getSRV(), // Albed GBuffer[1].getSRV(), // Normal GBuffer[2].getSRV(), // Depth GBuffer[3].getSRV(), // Diffuse }; // レンダリング時にアクセス可能なレンダー ターゲットのサブリソースを識別(Render Target View) ID3D11RenderTargetView *GBufferRTV [] = { GBuffer[0].getRTV(), // Albed GBuffer[1].getRTV(), // Normal GBuffer[2].getRTV(), // Depth GBuffer[3].getRTV(), // Diffuse }; // クリアの際に使用する ID3D11ShaderResourceView *NULLSRV[] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }; ID3D11RenderTargetView *NULLRTV[] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }; // パイプラインの構築 deferredGPL.setStatus(); //=====================================================// // ループ処理 //=====================================================// int ret = 0; while (ret != WM_QUIT){ ret = window.MessageLoop(); float clear [] = { 0.0f, 0.0f, 0.0f, 0.0f }; // パイプラインのクリア device.getContext()->OMSetRenderTargets(8, NULLRTV, nullptr); // レンダーターゲットのクリア device.getContext()->PSSetShaderResources(0,8, NULLSRV); // シェーダーリソースのクリア //バックバッファのクリア DEBUG(device.getAnotation()->BeginEvent(L"バッファのクリア")); device.getContext()->ClearRenderTargetView(device.getRTV(), clear); device.getContext()->ClearDepthStencilView(device.getDSV(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); //GBufferのクリア for (auto v : GBufferRTV) { device.getContext()->ClearRenderTargetView(v, clear); } DEBUG(device.getAnotation()->EndEvent()); //GUIのクリア ImGui_ImplDX11_NewFrame(); // デバッグ情報の出力 ImGui::Text("Debug Text"); ImGui::Text("Application.average %.3f ms/frame(%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); // FPS //通常描画で使うバッファの更新 // Bufferに更新をかける (コンスタントバッファを更新) device.getContext()->UpdateSubresource(constantbuffer, 0, NULL, &mtx, 0, 0); // CPU によって、マッピング不可能なメモリー内に作成されたサブリソースにメモリーからデータがコピーされる // Bufferをパイプラインにセット (シェーダーステージへのセット) device.getContext()->VSSetConstantBuffers(0, 1, &constantbuffer); // 頂点シェーダーのパイプライン ステージで使用される定数バッファーを設定 //通常描画の設定 device.getContext()->OMSetRenderTargets(4, GBufferRTV, nullptr); // 出力結合ステージに深度ステンシル バッファーをバインド UINT stride = sizeof(Vertex4UV); // 頂点のサイズ UINT offset = 0; // ずれの調整 device.getContext()->IASetVertexBuffers(0, 1, &vertexbuffer, &stride, &offset); // 入力アセンブラー ステージに頂点バッファーの配列をバインド device.getContext()->VSSetShader(vs_buf, nullptr, 0); // 頂点シェーダーをデバイスに設定 device.getContext()->PSSetShader(ps_buf, nullptr, 0); // ピクセル シェーダーをデバイスに設定 device.getContext()->IASetInputLayout(inputlayout); // 入力アセンブラー ステージに入力レイアウト オブジェクトをバインド //テクスチャの設定 ID3D11ShaderResourceView *srv [] = { // レンダリング時にシェーダーがアクセス可能なサブリソースを指定 tex.getSRV(), tex2.getSRV() }; device.getContext()->PSSetShaderResources(0, 2, srv); // ピクセル シェーダー ステージにシェーダー リソースの配列をバインド device.getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); // プリミティブ タイプおよびデータの順序に関する情報をバインド //通常描画 device.getContext()->Draw(4, 0);// 頂点数:何番目の頂点からやるか //ディファードの最終描画の設定 DEBUG(device.getAnotation()->BeginEvent(L"ディファードの最終合成")); ID3D11RenderTargetView *finalrtv [] = { device.getRTV(), }; device.getContext()->OMSetRenderTargets(1, finalrtv, nullptr); // // 出力結合ステージに深度ステンシル バッファーをバインド device.getContext()->IASetVertexBuffers(0, 1, &finalvertexbuffer, &stride, &offset); device.getContext()->VSSetShader(vsfinal_buf, nullptr, 0); // 頂点シェーダーをデバイスに設定 device.getContext()->PSSetShader(psfinal_buf, nullptr, 0); // ピクセル シェーダーをデバイスに設定 device.getContext()->IASetInputLayout(inputlayout); // // 入力アセンブラー ステージに入力レイアウト オブジェクトをバインド device.getContext()->PSSetShaderResources(0, 4, GBufferSRV); // ピクセル シェーダー ステージにシェーダー リソースの配列をバインド device.getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); // // プリミティブ タイプおよびデータの順序に関する情報をバインド //ディファードの最終描画 device.getContext()->Draw(4, 0);// 頂点数:何番目の頂点からやるか DEBUG(device.getAnotation()->EndEvent()); //Guiの描画 ImGui::Render(); //バックバッファとフロントバッファの切り替え device.getSwapChain()->Present(0, 0); } //=====================================================// // 解放処理 //=====================================================// //ImGuiの終了処理 ImGui_ImplDX11_Shutdown(); // マクロリリース SAFE_RELEASE(vertexbuffer); SAFE_RELEASE(finalvertexbuffer); SAFE_RELEASE(vs_buf); SAFE_RELEASE(ps_buf); SAFE_RELEASE(vsfinal_buf); SAFE_RELEASE(psfinal_buf); SAFE_RELEASE(inputlayout); SAFE_RELEASE(constantbuffer); deferredGPL.Release(); return ret; }
//================================================================================================================= bool TopdownTile::RenderFow(Camera* camera, float blendAmount, XMFLOAT2 offset) { /*ZShadeSandboxMesh::MeshRenderParameters mrp; mrp.camera = camera; mrp.blendAmount = blendAmount; mrp.specifyWorld = true; mrp.world = XMMatrixIdentity(); switch (m_fogBit)//m_fogBitShadow) { case fow_s_all: { if (fow_shadow_texture == NULL) return false; fow_shadow_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_texture->Render(mrp); } break; #pragma region "Shadow Straights" case fow_s_NNN: { if (fow_shadow_NNN_texture == NULL) return false; fow_shadow_NNN_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_NNN_texture->Render(mrp); } break; case fow_s_SSS: { if (fow_shadow_SSS_texture == NULL) return false; fow_shadow_SSS_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_SSS_texture->Render(mrp); } break; case fow_s_EEE: { if (fow_shadow_EEE_texture == NULL) return false; fow_shadow_EEE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_EEE_texture->Render(mrp); } break; case fow_s_WWW: { if (fow_shadow_WWW_texture == NULL) return false; fow_shadow_WWW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_WWW_texture->Render(mrp); } break; #pragma endregion #pragma region "Shadow Corners" case fow_s_CNW: { if (fow_shadow_CNW_texture == NULL) return false; fow_shadow_CNW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_CNW_texture->Render(mrp); } break; case fow_s_CNE: { if (fow_shadow_CNE_texture == NULL) return false; fow_shadow_CNE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_CNE_texture->Render(mrp); } break; case fow_s_CSW: { if (fow_shadow_CSW_texture == NULL) return false; fow_shadow_CSW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_CSW_texture->Render(mrp); } break; case fow_s_CSE: { if (fow_shadow_CSE_texture == NULL) return false; fow_shadow_CSE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_CSE_texture->Render(mrp); } break; #pragma endregion #pragma region "Shadow Joints" case fow_s_JNW: { if (fow_shadow_JNW_texture == NULL) return false; fow_shadow_JNW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_JNW_texture->Render(mrp); } break; case fow_s_JNE: { if (fow_shadow_JNE_texture == NULL) return false; fow_shadow_JNE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_JNE_texture->Render(mrp); } break; case fow_s_JSW: { if (fow_shadow_JSW_texture == NULL) return false; fow_shadow_JSW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_JSW_texture->Render(mrp); } break; case fow_s_JSE: { if (fow_shadow_JSE_texture == NULL) return false; fow_shadow_JSE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_shadow_JSE_texture->Render(mrp); } break; #pragma endregion /*} switch (m_fogBit) {* case fow_n_all: { if (fow_all_texture == NULL) return false; fow_all_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_all_texture->Render(mrp); } break; #pragma region "Straights" case fow_n_NNN: { if (fow_NNN_texture == NULL) return false; fow_NNN_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_NNN_texture->Render(mrp); } break; case fow_n_SSS: { if (fow_SSS_texture == NULL) return false; fow_SSS_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_SSS_texture->Render(mrp); } break; case fow_n_EEE: { if (fow_EEE_texture == NULL) return false; fow_EEE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_EEE_texture->Render(mrp); } break; case fow_n_WWW: { if (fow_WWW_texture == NULL) return false; fow_WWW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_WWW_texture->Render(mrp); } break; #pragma endregion #pragma region "Corners" case fow_n_CNW: { if (fow_CNW_texture == NULL) return false; fow_CNW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_CNW_texture->Render(mrp); } break; case fow_n_CNE: { if (fow_CNE_texture == NULL) return false; fow_CNE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_CNE_texture->Render(mrp); } break; case fow_n_CSW: { if (fow_CSW_texture == NULL) return false; fow_CSW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_CSW_texture->Render(mrp); } break; case fow_n_CSE: { if (fow_CSE_texture == NULL) return false; fow_CSE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_CSE_texture->Render(mrp); } break; #pragma endregion #pragma region "Joints" case fow_n_JNW: { if (fow_JNW_texture == NULL) return false; fow_JNW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_JNW_texture->Render(mrp); } break; case fow_n_JNE: { if (fow_JNE_texture == NULL) return false; fow_JNE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_JNE_texture->Render(mrp); } break; case fow_n_JSW: { if (fow_JSW_texture == NULL) return false; fow_JSW_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_JSW_texture->Render(mrp); } break; case fow_n_JSE: { if (fow_JSE_texture == NULL) return false; fow_JSE_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_JSE_texture->Render(mrp); } break; #pragma endregion }*/ if (mFOWMesh == NULL) return false; mFOWMesh->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); ZShadeSandboxMesh::MeshRenderParameters mrp; mrp.camera = camera; mrp.blendAmount = blendAmount; mrp.specifyWorld = true; mrp.world = XMMatrixIdentity(); mFOWMesh->Render(mrp); return true; }
virtual void PostRender() override { IRenderer* pRenderer = GLOBAL::Engine()->Renderer(); eTRANSFORM_MODE mode = GLOBAL::SelectionMgr()->GetTransformMode(); int FPS = GLOBAL::Engine()->GlobalTimer()->GetFPS(); RENDER_TEXT_QUAD textFPS; _itow_s(FPS, textFPS.strMsg, 5, 10); textFPS.rc.left = 0; textFPS.rc.top = 0; textFPS.rc.right = 100; textFPS.rc.bottom = 100; textFPS.clr = CColor( 1.0f, 1.0f, 1.0f, 1.0f ); pRenderer->RenderText(&textFPS); pRenderer->RenderWorldGrid( XMMatrixIdentity(), 5000, 100 ); TYPE_SELECTED_ENTITIES* selcetedEntities = GLOBAL::SelectionMgr()->List(); for( UINT i=0; i< selcetedEntities->size() ; ++i) { IEntity* pEntity = (*selcetedEntities)[i]; // Draw transform helper CQuat rot; XMMATRIX tm = XMMatrixIdentity(); tm.r[3] = pEntity->GetWorldTM().r[3]; if( mode == TRANSFORM_MOVE) { pRenderer->RenderMover( tm ); } else if( mode == TRANSFORM_ROTATE) { pRenderer->RenderRotator( tm); } else if( mode == TRANSFORM_SCALE) { pRenderer->RenderScaler( tm ); } pRenderer->RenderAxis( pEntity->GetWorldTM() ); const CAABB* pWorldAABB = pEntity->GetWorldAABB(); // Draw Bounding Box if( pWorldAABB->IsValid() ) { pRenderer->RenderBox( XMMatrixIdentity(), pWorldAABB->GetMin(), pWorldAABB->GetMax() ,COLOR_GRAY ); const CAABB* pLocalEntityAABB = pEntity->GetLocalEntityAABB(); if( pLocalEntityAABB->IsValid() ) pRenderer->RenderBox( pEntity->GetWorldTM(), pLocalEntityAABB->GetMin(), pLocalEntityAABB->GetMax() ,COLOR_WHITE ); } // Draw skeleton if it has a actor IEntityProxyActor* pActor = (IEntityProxyActor*)pEntity->GetProxy(ENTITY_PROXY_ACTOR); if( pActor != NULL) { JOINT_ENTITY_LIST* pJointEntitesList = pActor->GetJointEntities(); CVertexPC buff[512]; int vertIndex = 0; for( UINT i=1; i < pJointEntitesList->size(); ++i) { buff[vertIndex].vPos = (*pJointEntitesList)[i]->GetWorldPos(); buff[vertIndex].color = COLOR_RED; vertIndex++; buff[vertIndex].vPos = (*pJointEntitesList)[i]->GetParent()->GetWorldPos(); buff[vertIndex].color = COLOR_RED; vertIndex++; } pRenderer->RenderLine( buff, vertIndex ); } } { /* const LIGHT_LIST* pLightList = GLOBAL::Engine()->LightMgr()->GetVisibleLights(); for( UINT i =0; i < pLightList->size(); ++i ) { CLightDesc* pLightDesc = (*pLightList)[i]; pRenderer->RenderSphere( &pLightDesc->pos, pLightDesc->range ); }*/ } }
void CGLImpl::InitializeMatrix(xe_matrix_t *m) { // initializes a matrix to a known state prior to rendering m->dirty = 1; m->stackdepth = 0; m->stack[0] = XMMatrixIdentity(); }
bool TestTriangleStripsDX::InitScene() { XMStoreFloat4(&up, XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f)); XMStoreFloat4(&eye, XMVectorSet(0.0f, 18.0f, 18.0f, 1.0f)); XMStoreFloat4(&right, XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f)); XMStoreFloat4(¢er, XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f)); bg[0] = bgColor.r; bg[1] = bgColor.g; bg[2] = bgColor.b; bg[3] = bgColor.a; ID3D11RasterizerState1 *rasterizerState; D3D11_RASTERIZER_DESC1 rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc)); rasterizerDesc.CullMode = D3D11_CULL_NONE; rasterizerDesc.FillMode = D3D11_FILL_SOLID; rasterizerDesc.FrontCounterClockwise = true; mDevice->CreateRasterizerState1(&rasterizerDesc, &rasterizerState); mDeviceContext->RSSetState(rasterizerState); rasterizerState->Release(); BinaryIO::ReadVector4s(binaryPath + "triangle_strip_plane.bin", vertices); D3D11_INPUT_ELEMENT_DESC vertexLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; D3DCompileFromFile(Util::s2ws(shaderPath + "TestTriangleStripsVert.hlsl").c_str(), NULL, NULL, "vertexShader", "vs_5_0", NULL, NULL, &vertexShaderBuffer, NULL); D3DCompileFromFile(Util::s2ws(shaderPath + "TestTriangleStripsFrag.hlsl").c_str(), NULL, NULL, "pixelShader", "ps_5_0", NULL, NULL, &pixelShaderBuffer, NULL); mDevice->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &vertexShader); mDevice->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &pixelShader); D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.ByteWidth = vertices.size() * sizeof(Vector4); vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA vertexBufferData; ZeroMemory(&vertexBufferData, sizeof(vertexBufferData)); vertexBufferData.pSysMem = &vertices[0]; mDevice->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &vertexBuffer); mDevice->CreateInputLayout(vertexLayout, 1, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &inputLayout); // UPLOAD MVP MATRICES XMMATRIX modelMatrix = XMMatrixIdentity(); XMMATRIX viewMatrix = XMMatrixLookAtRH(XMLoadFloat4(&eye), XMLoadFloat4(¢er), XMLoadFloat4(&up)); XMMATRIX projectionMatrix = XMMatrixPerspectiveFovRH(XMConvertToRadians(60.0f), 800 / 800, 1.0f, 500.0f); ID3D11Buffer* modelMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, modelMatrix); mDeviceContext->VSSetConstantBuffers(modelMatrixBufferSlot, 1, &modelMatrixBuffer); modelMatrixBuffer->Release(); viewMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, viewMatrix); mDeviceContext->VSSetConstantBuffers(viewMatrixBufferSlot, 1, &viewMatrixBuffer); viewMatrixBuffer->Release(); ID3D11Buffer* projectionMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, projectionMatrix); mDeviceContext->VSSetConstantBuffers(projectionMatrixBufferSlot, 1, &projectionMatrixBuffer); projectionMatrixBuffer->Release(); return true; }
CFraps* g_pFraps; CBackground* g_pBackground; GLuint g_WvpAndColorProgram; WVP_COLOR_UNIFORMS g_WvpAndColorUniforms; GLuint g_PhongProgram; PHONG_UNIFORMS g_PhongUniforms; float g_ElapsedTime = 0.0f; POINT_LIGHT_SOURCE g_PointLights[MAX_POINT_LIGHTS]; float g_Distance = -3.3f; float g_SpinX; float g_SpinY; XMMATRIX g_View = XMMatrixIdentity(); XMMATRIX g_Proj = XMMatrixIdentity(); GLuint g_LightCount = 2; // // LoadShaders // bool LoadShaders() { puts("Load shaders"); GLuint vsh, fsh; bool bLinked; // // Transform'n'Color program
void MyApp::renderScene() { static float time = 0.0f; if (!m_bPaused) time += 0.001f; // Clear the back buffer float clearColor[3] = { 0.4f, 0.4f, 0.7f }; float clearColorBlack[3] = { 0.f, 0.f, 0.f }; _dxImmedDC->ClearRenderTargetView(_renderTargetView, (float*)&clearColorBlack); _dxImmedDC->ClearDepthStencilView(_depthStencilView, D3D11_CLEAR_DEPTH, 1, 0); _dxImmedDC->OMSetBlendState(0, 0, 0xffffffff); _dxImmedDC->RSSetState(0); // Bind the input layout _dxImmedDC->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); XMMATRIX mVP = m_camera.getViewMatrix()*m_camera.getProjectionMatrix(); //_______I m p l i c i t O b j e c t s_____________ drawImplicitToTexture(); setMatrixVar(m_fxQuads, (void*)&mVP, "mViewProj"); setSrvArrayVar(m_fxQuads, &m_srvImplicit, "texarrObjects", 0, 5); _dxImmedDC->IASetInputLayout(0); _dxImmedDC->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST); ID3DX11EffectTechnique* tech; tech = m_fxQuads->GetTechniqueByIndex(0); tech->GetPassByIndex(0)->Apply(0, _dxImmedDC); _dxImmedDC->Draw(4, 0); //_______T e s s e l l a t e d O b j e c t s _______ if (glb_bWireframe) _dxImmedDC->RSSetState(rs_Wireframe); // Scene - Spheres for (unsigned int i=0; i<m_spheres.size(); i++) { drawTessSphereFromOct(&(m_spheres[i])); } myAlien.setPos(0,30,0); if (myAlien.type == AlienTypes::GS_ALIEN) drawMesh(myAlien.mesh, m_fxAlienGS, myAlien.getMatrix()); else if (myAlien.type == AlienTypes::EXP_ALIEN) { drawMesh(myAlien.mesh, m_fxExplosion, myAlien.getMatrix(), myAlien.expl_time); myAlien.expl_time += 0.001f; } XMFLOAT4X4 mI; XMStoreFloat4x4(&mI, XMMatrixIdentity()); // Scene - Aliens for (unsigned int i=0; i<m_aliens.size(); i++) { if (m_aliens[i].type == AlienTypes::VS_ALIEN) drawMesh(m_aliens[i].mesh, m_fxAlienVS, m_aliens[i].getMatrix()); else if (m_aliens[i].type == AlienTypes::GS_ALIEN) drawMesh(m_aliens[i].mesh, m_fxAlienGS, m_aliens[i].getMatrix()); else if (m_aliens[i].type == AlienTypes::HS_ALIEN) drawTessMesh(m_aliens[i].getMatrix()); else if (m_aliens[i].type == AlienTypes::EXP_ALIEN) { drawMesh(m_aliens[i].mesh, m_fxExplosion, m_aliens[i].getMatrix(), m_aliens[i].expl_time); m_aliens[i].expl_time += 0.001f; } else if (m_aliens[i].type == AlienTypes::BEZ_ALIEN) // BEZ_ALIEN drawTessBezierSurface(m_aliens[i].getPos(), m_aliens[i].getTargetPos()); else // PSP_ALIEN drawPSPSurface(m_aliens[i].getPos(), m_aliens[i].getTargetPos()); } // PSP Surface if (glb_bSphereMesh) drawTessSphereFromMesh(); // Terrain editTerrain(); drawTessTerrain(); //_______ G U I ______________________________________ TwDraw(); // Swap Buffer _swapChain->Present(0, 0); }
bool SpriteGame::loadContent() { CComPtr<ID3DBlob> compiledShader(compileShader("SpriteShader.fx", "VS_Main", "vs_4_0")); if(compiledShader == nullptr) return false; HRESULT result = device->CreateVertexShader(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), nullptr, &vertexShader); if(FAILED(result)) return false; D3D11_INPUT_ELEMENT_DESC vertexProperties[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXEL", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; result = device->CreateInputLayout(vertexProperties, 2, compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), &inputLayout); if(FAILED(result)) return false; compiledShader = compileShader("SpriteShader.fx", "PS_Main", "ps_4_0"); if(compiledShader == nullptr) return false; result = device->CreatePixelShader(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), nullptr, &pixelShader); if(FAILED(result)) return false; result = D3DX11CreateShaderResourceViewFromFile(device, "Resources/Sprite.dds", nullptr, nullptr, &texture, nullptr); if(FAILED(result)) return false; D3D11_SAMPLER_DESC samplerDescriptor; ZeroMemory(&samplerDescriptor, sizeof(samplerDescriptor)); samplerDescriptor.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDescriptor.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDescriptor.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDescriptor.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDescriptor.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDescriptor.MaxLOD = D3D11_FLOAT32_MAX; result = device->CreateSamplerState(&samplerDescriptor, &textureSampler); if(FAILED(result)) return false; CComPtr<ID3D11Resource> textureResource; texture->GetResource(&textureResource); D3D11_TEXTURE2D_DESC textureDescriptor; ((ID3D11Texture2D*)(textureResource.p))->GetDesc(&textureDescriptor); float halfWidth = textureDescriptor.Width/2.0f; float halfHeight = textureDescriptor.Height/2.0f; Vertex vertices[] = { { XMFLOAT3(-halfWidth, halfHeight, 1.0f), XMFLOAT2(0.0f, 0.0f) }, { XMFLOAT3( halfWidth, halfHeight, 1.0f), XMFLOAT2(1.0f, 0.0f) }, { XMFLOAT3(-halfWidth, -halfHeight, 1.0f), XMFLOAT2(0.0f, 1.0f) }, { XMFLOAT3( halfWidth, -halfHeight, 1.0f), XMFLOAT2(1.0f, 1.0f) } }; D3D11_BUFFER_DESC bufferDescriptor = {0}; bufferDescriptor.Usage = D3D11_USAGE_DEFAULT; bufferDescriptor.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDescriptor.ByteWidth = sizeof(vertices); D3D11_SUBRESOURCE_DATA vertexData = {0}; vertexData.pSysMem = vertices; result = device->CreateBuffer(&bufferDescriptor, &vertexData, &vertexBuffer); if(FAILED(result)) return false; D3D11_BUFFER_DESC matrixBufferDescriptor = {0}; matrixBufferDescriptor.Usage = D3D11_USAGE_DEFAULT; matrixBufferDescriptor.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDescriptor.ByteWidth = sizeof(XMMATRIX); result = device->CreateBuffer(&matrixBufferDescriptor, nullptr, &mvpMatrixBuffer); if(FAILED(result)) return false; sprites[0].setPosition(100, 300); sprites[1].setPosition(400, 100); vpMatrix = XMMatrixIdentity() * XMMatrixOrthographicOffCenterLH(0.0f, 600.0f, 0.0f, 600.0f, 0.1f, 100.0f); D3D11_BLEND_DESC blendDescriptor = {0}; blendDescriptor.RenderTarget[0].BlendEnable = true; blendDescriptor.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDescriptor.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDescriptor.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendDescriptor.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDescriptor.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; blendDescriptor.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendDescriptor.RenderTarget[0].RenderTargetWriteMask = 0x0F; float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; device->CreateBlendState(&blendDescriptor, &blendState); deviceContext->OMSetBlendState(blendState, blendFactor, 0xFFFFFFFF); return true; }
void EntityComposite::render() { //get view and projection matrices XMMATRIX viewMatrix, projectionMatrix; GRAPHICS->getCamera()->GetViewMatrix(viewMatrix); GRAPHICS->getDirectXWrapper()->getProjectionMatrix(projectionMatrix); //compute position and orientation of the actor vector<snICollider*> colliders = m_actor->getColliders(); for (vector<snICollider*>::const_iterator i = colliders.cbegin(); i != colliders.cend(); ++i) { snMatrix44f temp = (*i)->getTransform().getLocalToWorld(); snMatrix44f scale; IGfxEntity* gfx = 0; switch ((*i)->getTypeOfCollider()) { case snEColliderType::snEColliderBox: { snOBB* box = static_cast<snOBB*>((*i)); scale.createScale(box->getExtends() * 2); gfx = GRAPHICS->getBox(); } break; case snEColliderType::snEColliderSphere: { snSphere* sphere = static_cast<snSphere*>((*i)); scale.createScale(sphere->getRadius() * 2); gfx = GRAPHICS->getSphere(); } break; case snEColliderType::snEColliderCapsule: { snCapsule* capsule = static_cast<snCapsule*>((*i)); float diameter = capsule->getRadius() * 2; //draw the first sphere scale.createScale(diameter); snMatrix44f translate; translate.createTranslation(capsule->getFirstEndPoint()); snMatrix44f worldTransform; snMatrixMultiply4(scale, translate, worldTransform); XMMATRIX dxWorldMatrix; dxWorldMatrix.r[0] = worldTransform.m_r[0]; dxWorldMatrix.r[1] = worldTransform.m_r[1]; dxWorldMatrix.r[2] = worldTransform.m_r[2]; dxWorldMatrix.r[3] = worldTransform.m_r[3]; gfx = GRAPHICS->getSphere(); gfx->render(dxWorldMatrix, viewMatrix, projectionMatrix, m_color, m_texture, m_wireframe); //draw the second sphere translate.createTranslation(capsule->getSecondEndPoint()); snMatrixMultiply4(scale, translate, worldTransform); dxWorldMatrix.r[0] = worldTransform.m_r[0]; dxWorldMatrix.r[1] = worldTransform.m_r[1]; dxWorldMatrix.r[2] = worldTransform.m_r[2]; dxWorldMatrix.r[3] = worldTransform.m_r[3]; gfx->render(dxWorldMatrix, viewMatrix, projectionMatrix, m_color, m_texture, m_wireframe); //prepare the capsule float length = Supernova::Vector::snVec3Norme(capsule->getFirstEndPoint() - capsule->getSecondEndPoint()); scale.createScale(Supernova::Vector::snVec4Set(capsule->getRadius(), length, capsule->getRadius(), 1)); gfx = GRAPHICS->getCylinder(); } break; default: continue; } snMatrix44f worldTransform; snMatrixMultiply4(scale, temp, worldTransform); XMMATRIX dxWorldMatrix; dxWorldMatrix.r[0] = worldTransform.m_r[0]; dxWorldMatrix.r[1] = worldTransform.m_r[1]; dxWorldMatrix.r[2] = worldTransform.m_r[2]; dxWorldMatrix.r[3] = worldTransform.m_r[3]; gfx->render(dxWorldMatrix, viewMatrix, projectionMatrix, m_color, m_texture, m_wireframe); } //render the center of mass XMMATRIX centerOfMassPosition = XMMatrixIdentity(); centerOfMassPosition.r[3] = m_actor->getWorldCenterOfMass(); m_gfxCenterOfMass->render(centerOfMassPosition, viewMatrix, projectionMatrix, Colors::Green, m_texture, m_wireframe); }
bool D3D::Initialize(HWND hWnd, Settings *pSettings) { HRESULT result; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; unsigned int numModes, i, numerator, denominator; unsigned long long stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; int error; DXGI_SWAP_CHAIN_DESC swapChainDesc; D3D_FEATURE_LEVEL featureLevel; ID3D11Texture2D* backBufferPtr; D3D11_TEXTURE2D_DESC depthBufferDesc; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; D3D11_RASTERIZER_DESC rasterDesc; D3D11_VIEWPORT viewport; float fieldOfView, screenAspect; m_pSettings = pSettings; m_hWnd = hWnd; // Create a DirectX graphics interface factory. result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) { return false; } // Use the factory to create an adapter for the primary graphics interface (video card). result = factory->EnumAdapters(0, &adapter); if (FAILED(result)) { return false; } // Enumerate the primary adapter output (monitor). result = adapter->EnumOutputs(0, &adapterOutput); if (FAILED(result)) { return false; } // Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if (FAILED(result)) { return false; } // Create a list to hold all the possible display modes for this monitor/video card combination. displayModeList = new DXGI_MODE_DESC[numModes]; if (!displayModeList) { return false; } // Now fill the display mode list structures. result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if (FAILED(result)) { return false; } // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the numerator and denominator of the refresh rate for that monitor. for (i = 0; i<numModes; i++) { if (displayModeList[i].Width == (unsigned int)m_pSettings->GetScreenWidth()) { if (displayModeList[i].Height == (unsigned int)m_pSettings->GetScreenHeight()) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } } // Get the adapter (video card) description. result = adapter->GetDesc(&adapterDesc); if (FAILED(result)) { return false; } // Store the dedicated video card memory in megabytes. m_VideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. error = wcstombs_s(&stringLength, m_VideoCardDescription, 128, adapterDesc.Description, 128); if (error != 0) { return false; } // Release the display mode list. delete[] displayModeList; displayModeList = 0; // Release the adapter output. adapterOutput->Release(); adapterOutput = 0; // Release the adapter. adapter->Release(); adapter = 0; // Release the factory. factory->Release(); factory = 0; // Initialize the swap chain description. ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // Set to a single back buffer. swapChainDesc.BufferCount = 1; // Set the width and height of the back buffer. swapChainDesc.BufferDesc.Width = m_pSettings->GetScreenWidth(); swapChainDesc.BufferDesc.Height = m_pSettings->GetScreenHeight(); // Set regular 32-bit surface for the back buffer. swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // Set the refresh rate of the back buffer. if (m_pSettings->GetVSync()) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } // Set the usage of the back buffer. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Set the handle for the window to render to. swapChainDesc.OutputWindow = hWnd; // Turn multisampling off. swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; // Set to full screen or windowed mode. if (m_pSettings->GetFullscreen()) { swapChainDesc.Windowed = false; } else { swapChainDesc.Windowed = true; } // Set the scan line ordering and scaling to unspecified. swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Discard the back buffer contents after presenting. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Don't set the advanced flags. swapChainDesc.Flags = 0; // Set the feature level to DirectX 11. featureLevel = D3D_FEATURE_LEVEL_11_0; // Create the swap chain, Direct3D device, and Direct3D device context. result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_SwapChain, &m_Device, NULL, &m_DeviceContext); if (FAILED(result)) { return false; } // Get the pointer to the back buffer. result = m_SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if (FAILED(result)) { return false; } // Create the render target view with the back buffer pointer. result = m_Device->CreateRenderTargetView(backBufferPtr, NULL, &m_RenderTargetView); if (FAILED(result)) { return false; } // Release pointer to the back buffer as we no longer need it. backBufferPtr->Release(); backBufferPtr = 0; // Initialize the description of the depth buffer. ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); // Set up the description of the depth buffer. depthBufferDesc.Width = m_pSettings->GetScreenWidth(); depthBufferDesc.Height = m_pSettings->GetScreenHeight(); depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; // Create the texture for the depth buffer using the filled out description. result = m_Device->CreateTexture2D(&depthBufferDesc, NULL, &m_DepthStencilBuffer); if (FAILED(result)) { return false; } // Initialize the description of the stencil state. ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); // Set up the description of the stencil state. depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing. depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing. depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Create the depth stencil state. result = m_Device->CreateDepthStencilState(&depthStencilDesc, &m_DepthStencilState); if (FAILED(result)) { return false; } // Set the depth stencil state. m_DeviceContext->OMSetDepthStencilState(m_DepthStencilState, 1); // Initialize the depth stencil view. ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); // Set up the depth stencil view description. depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; // Create the depth stencil view. result = m_Device->CreateDepthStencilView(m_DepthStencilBuffer, &depthStencilViewDesc, &m_DepthStencilView); if (FAILED(result)) { return false; } // Bind the render target view and depth stencil buffer to the output render pipeline. m_DeviceContext->OMSetRenderTargets(1, &m_RenderTargetView, m_DepthStencilView); // Setup the raster description which will determine how and what polygons will be drawn. rasterDesc.AntialiasedLineEnable = false; rasterDesc.CullMode = D3D11_CULL_BACK; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; // Create the rasterizer state from the description we just filled out. result = m_Device->CreateRasterizerState(&rasterDesc, &m_RasterState); if (FAILED(result)) { return false; } // Now set the rasterizer state. m_DeviceContext->RSSetState(m_RasterState); // Setup the viewport for rendering. viewport.Width = (float)m_pSettings->GetScreenWidth(); viewport.Height = (float)m_pSettings->GetScreenHeight(); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; // Create the viewport. m_DeviceContext->RSSetViewports(1, &viewport); // Setup the projection matrix. fieldOfView = 3.141592654f / 4.0f; screenAspect = (float)m_pSettings->GetScreenWidth() / (float)m_pSettings->GetScreenHeight(); // Create the projection matrix for 3D rendering. m_ProjectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, m_pSettings->GetScreenNear(), m_pSettings->GetScreenDepth()); // Initialize the world matrix to the identity matrix. m_WorldMatrix = XMMatrixIdentity(); // Create an orthographic projection matrix for 2D rendering. m_OrthoMatrix = XMMatrixOrthographicLH((float)m_pSettings->GetScreenWidth(), (float)m_pSettings->GetScreenHeight(), m_pSettings->GetScreenNear(), m_pSettings->GetScreenDepth()); return true; }
SpriteGame::SpriteGame() : vertexBuffer(nullptr), inputLayout(nullptr), vertexShader(nullptr), pixelShader(nullptr), texture(nullptr), textureSampler(nullptr), blendState(nullptr), mvpMatrixBuffer(nullptr) { vpMatrix = XMMatrixIdentity(); }
void Platform2::Initialize(int id, XMFLOAT3 pos) { Platform::Initialize(id, pos); //------------------------------------ // Create lights //------------------------------------ PointLight pLight1; pLight1.Position = pos; pLight1.Position.x += 147.414; pLight1.Position.y += -31.894f; pLight1.Position.z += -74.978f; mPointLights.push_back(pLight1); mPointLightOffsets.push_back(XMFLOAT3(147.414, -31.894f, -74.978f)); for (UINT i = 0; i < mPointLights.size(); ++i) { mPointLights[i].Ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f); mPointLights[i].Diffuse = XMFLOAT4(0.7f, 0.7f, 0.7f, 1.0f); mPointLights[i].Specular = XMFLOAT4(0.7f, 0.7f, 0.7f, 1.0f); mPointLights[i].Attenuation = XMFLOAT3(0.0f, 0.1f, 0.0f); mPointLights[i].Range = 250.0f; } int index = 0; XMFLOAT4X4 rot; XMStoreFloat4x4(&rot, XMMatrixIdentity()); PlatformSwitch* ps = new PlatformSwitch(); this->mSwitches.push_back(ps); this->mSwitches.at(index)->Initialize(pos, XMFLOAT3(-129.8f, -0.95f, -91.9f), 3, 8, rot, XMFLOAT3(0, 0, 0)); index++; ///////////////////////////////////////////////////////////////////// PlatformSwitch* ps1 = new PlatformSwitch(); this->mSwitches.push_back(ps1); this->mSwitches.at(index)->Initialize(pos, XMFLOAT3(8.64f, -48.578f, -91.851f), 1, 4, rot, XMFLOAT3(0, -5.0f, 0.0f)); this->mSwitches.at(index)->getEntity()->RotateEntityX(-XM_PI/2); index++; /////////////////////////////////////////////////////////7 PlatformSwitch* ps2 = new PlatformSwitch(); this->mSwitches.push_back(ps2); this->mSwitches.at(index)->Initialize(pos, XMFLOAT3(-33.338f, -48.542f, 91.95f), 1, 3, rot, XMFLOAT3(0, -5.0f, 5.0f)); this->mSwitches.at(index)->getEntity()->RotateEntityX(XM_PI); index++; /////////////////////////////////////////////////////// //ok PlatformSwitch* ps3 = new PlatformSwitch(); this->mSwitches.push_back(ps3); this->mSwitches.at(index)->Initialize(pos, XMFLOAT3(-129.957f, 21.513f, 91.85f), 3, 10, rot, XMFLOAT3(-5.0f, 0.0f, 5.0f)); this->mSwitches.at(index)->getEntity()->RotateEntityY(XM_PI/2); index++; //////////////////////////////////////////////////// //ok PlatformSwitch* ps4 = new PlatformSwitch(); this->mSwitches.push_back(ps4); this->mSwitches.at(index)->Initialize(pos, XMFLOAT3(53.692f, -3.895f, 91.876f), 3, 9, rot, XMFLOAT3(5.0f, 0.0f, 5.0f)); this->mSwitches.at(index)->getEntity()->RotateEntityY(XM_PI); index++; ////////////////////////////////////////////////////// //ok PlatformSwitch* ps5 = new PlatformSwitch(); this->mSwitches.push_back(ps5); this->mSwitches.at(index)->Initialize(pos, XMFLOAT3(-54.435f, 48.159f, -91.851f), 1, 1, rot, XMFLOAT3(0, 0.0f, 0.0f)); index++; ////////////////////////////////////////////////////////////////// //ok PlatformSwitch* ps6 = new PlatformSwitch(); this->mSwitches.push_back(ps6); this->mSwitches.at(index)->Initialize(pos, XMFLOAT3(53.832f, 48.159f, -8.432f), 2, 5, rot, XMFLOAT3(0, 0.0f, 0.0f)); index++; }
SimpleVertexShader::SimpleVertexShader(void) { // Initialise constant buffer data XMStoreFloat4x4( &m_cbPerObjectData.m_worldViewProjection, XMMatrixIdentity() ); m_cbPerObjectData.m_colour = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f); }
// 프로그래머블 셰이더 작성 HRESULT MakeShaders( void ) { HRESULT hr; ID3DBlob* pVertexShaderBuffer = NULL; ID3DBlob* pPixelShaderBuffer = NULL; ID3DBlob* pError = NULL; DWORD dwShaderFlags = 0; #ifdef _DEBUG dwShaderFlags |= D3DCOMPILE_DEBUG; #endif // 컴파일 hr = D3DX11CompileFromFile( _T( "Basic_2D.fx" ), NULL, NULL, "VS", "vs_4_0_level_9_1", dwShaderFlags, 0, NULL, &pVertexShaderBuffer, &pError, NULL ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't open Basic_2D.fx" ), _T( "Error" ), MB_OK ); SAFE_RELEASE( pError ); return hr; } hr = D3DX11CompileFromFile( _T( "Basic_2D.fx" ), NULL, NULL, "PS", "ps_4_0_level_9_1", dwShaderFlags, 0, NULL, &pPixelShaderBuffer, &pError, NULL ); if ( FAILED( hr ) ) { SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pError ); return hr; } SAFE_RELEASE( pError ); // VertexShader 작성 hr = g_pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), NULL, &g_pVertexShader ); if ( FAILED( hr ) ) { SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); return hr; } // PixelShader 작성 hr = g_pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(), pPixelShaderBuffer->GetBufferSize(), NULL, &g_pPixelShader ); if ( FAILED( hr ) ) { SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); return hr; } // 입력 버퍼의 입력 형식 D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE( layout ); // 입력 버퍼의 입력 형식 작성 hr = g_pd3dDevice->CreateInputLayout( layout, numElements, pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), &g_pInputLayout ); SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); if ( FAILED( hr ) ) { return hr; } // 셰이더 상수 버퍼 작성 D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof( bd ) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( CBNeverChanges ); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pCBNeverChanges ); if( FAILED( hr ) ) return hr; // 변환행렬 CBNeverChanges cbNeverChanges; XMMATRIX mScreen; mScreen = XMMatrixIdentity(); mScreen._11 = 2.0f / g_nClientWidth; mScreen._22 = -2.0f / g_nClientHeight; mScreen._41 = -1.0f; mScreen._42 = 1.0f; cbNeverChanges.mView = XMMatrixTranspose( mScreen ); g_pImmediateContext->UpdateSubresource( g_pCBNeverChanges, 0, NULL, &cbNeverChanges, 0, 0 ); return S_OK; }
void CActorPlane::OnLoad() { /*ID3DBlob* d3dVertexShaderBlob = NULL; HRESULT hResult = Graphics->CompileShaderFromFile(L"SimpleShader.fx", "VS", "vs_4_0", &d3dVertexShaderBlob); if (FAILED(hResult)) { MessageBox(NULL, L"No se pudo compilar shader.", L"Error", MB_OK ); Game->Exit(); } // Se crea el vertex shader hResult = Graphics->GetDevice()->CreateVertexShader( d3dVertexShaderBlob->GetBufferPointer(), d3dVertexShaderBlob->GetBufferSize(), NULL, &this->d3dVertexShader ); if( FAILED( hResult ) ) { d3dVertexShaderBlob->Release(); Game->Exit(); } // Define cómo entrarán // los datos al shader D3D11_INPUT_ELEMENT_DESC a_d3dLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, //El 12 de aquí indica el número de bytes que hay entre //el comienzo del buffer y los datos a los que se hace //la referencia. Por ejemplo, hay un Vector de 3 elementos //de tipo flotante. Los float son de 4 bytes, entonces 4x3=12 //y es por eso que se pone aquí un 12, que es donde comienza //el vector de color. { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE( a_d3dLayout ); //Se crea el input layout hResult = Graphics->GetDevice()->CreateInputLayout( a_d3dLayout, numElements, d3dVertexShaderBlob->GetBufferPointer(), d3dVertexShaderBlob->GetBufferSize(), &this->d3dInputLayout ); //Ya no se ocupará d3dVertexShaderBlob->Release(); if(FAILED(hResult)) Game->Exit(); Graphics->GetDeviceContext()->IASetInputLayout(this->d3dInputLayout); ID3DBlob* d3dPixelShaderBlob = NULL; hResult = Graphics->CompileShaderFromFile( L"SimpleShader.fx", "PS", "ps_4_0", &d3dPixelShaderBlob ); if(FAILED(hResult)) { MessageBox( NULL, L"No se pudo compilar shader.", L"Error", MB_OK ); Game->Exit(); } // Create the pixel shader hResult = Graphics->GetDevice()->CreatePixelShader( d3dPixelShaderBlob->GetBufferPointer(), d3dPixelShaderBlob->GetBufferSize(), NULL, &this->d3dPixelShader ); d3dPixelShaderBlob->Release(); if (FAILED(hResult)) Game->Exit(); // Create vertex buffer SimpleVertex a_sVertices[] = { { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.0f, 0.0f, 1.0f, 1.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.0f, 1.0f, 0.0f, 1.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 1.0f, 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT4( 1.0f, 0.0f, 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 0.0f, 1.0f, 1.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 0.0f, 1.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ) }, }; //Buffer Descriptor: //Configura un recurso, en este caso //un buffer de vertices e índices D3D11_BUFFER_DESC d3dBufferDescriptor; ZeroMemory( &d3dBufferDescriptor, sizeof(d3dBufferDescriptor) ); //Lectura y escritura del buffer en el shader d3dBufferDescriptor.Usage = D3D11_USAGE_DEFAULT; d3dBufferDescriptor.ByteWidth = sizeof( SimpleVertex ) * 8; d3dBufferDescriptor.BindFlags = D3D11_BIND_VERTEX_BUFFER; d3dBufferDescriptor.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA d3dInitData; ZeroMemory( &d3dInitData, sizeof(d3dInitData) ); d3dInitData.pSysMem = a_sVertices; hResult = Graphics->GetDevice()->CreateBuffer( &d3dBufferDescriptor, &d3dInitData, &this->d3dVertexBuffer ); if( FAILED( hResult ) ) Game->Exit(); UINT uiStride = sizeof( SimpleVertex ); UINT uiOffset = 0; Graphics->GetDeviceContext()->IASetVertexBuffers( 0, 1, &this->d3dVertexBuffer, &uiStride, &uiOffset ); // Creamos buffer de indices usando el mismo //descriptor WORD a_wIndices[] = { 3,1,0, 2,1,3, 0,5,4, 1,5,0, 3,4,7, 0,4,3, 1,6,5, 2,6,1, 2,7,6, 3,7,2, 6,4,5, 7,4,6, }; d3dBufferDescriptor.Usage = D3D11_USAGE_DEFAULT; d3dBufferDescriptor.ByteWidth = sizeof( WORD ) * 36; // 36 vertices needed for 12 triangles in a triangle list d3dBufferDescriptor.BindFlags = D3D11_BIND_INDEX_BUFFER; d3dBufferDescriptor.CPUAccessFlags = 0; d3dInitData.pSysMem = a_wIndices; hResult = Graphics->GetDevice()->CreateBuffer( &d3dBufferDescriptor, &d3dInitData, &this->d3dIndexBuffer ); if( FAILED( hResult ) ) Game->Exit(); // Set index buffer Graphics->GetDeviceContext()->IASetIndexBuffer( this->d3dIndexBuffer, DXGI_FORMAT_R16_UINT, 0 ); // Set topología de primitiva Graphics->GetDeviceContext()->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); // Creamos el constant buffer d3dBufferDescriptor.Usage = D3D11_USAGE_DEFAULT; d3dBufferDescriptor.ByteWidth = sizeof(MatrixBuffer); d3dBufferDescriptor.BindFlags = D3D11_BIND_CONSTANT_BUFFER; d3dBufferDescriptor.CPUAccessFlags = 0; hResult = Graphics->GetDevice()->CreateBuffer( &d3dBufferDescriptor, NULL, &this->d3dConstantBuffer ); if( FAILED( hResult ) ) Game->Exit();*/ this->mxWorld = XMMatrixIdentity(); }
//-------------------------------------------------------------------------------------- // Create Direct3D device and swap chain //-------------------------------------------------------------------------------------- HRESULT InitDevice() { HRESULT hr = S_OK; RECT rc; GetClientRect( g_hWnd, &rc ); UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = ARRAYSIZE( driverTypes ); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE( featureLevels ); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) { g_driverType = driverTypes[driverTypeIndex]; hr = D3D11CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext ); if( SUCCEEDED( hr ) ) break; } if( FAILED( hr ) ) return hr; // Create a render target view ID3D11Texture2D* pBackBuffer = NULL; hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); if( FAILED( hr ) ) return hr; hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView ); pBackBuffer->Release(); if( FAILED( hr ) ) return hr; //create z buffer // Create depth stencil texture D3D11_TEXTURE2D_DESC descDepth; ZeroMemory( &descDepth, sizeof(descDepth) ); descDepth.Width = width; descDepth.Height = height; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepth.SampleDesc.Count = 1; descDepth.SampleDesc.Quality = 0; descDepth.Usage = D3D11_USAGE_DEFAULT; descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil ); if( FAILED( hr ) ) return hr; // Create the depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; ZeroMemory( &descDSV, sizeof(descDSV) ); descDSV.Format = descDepth.Format; descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView ); if( FAILED( hr ) ) return hr; g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView ); // Setup the viewport D3D11_VIEWPORT vp; vp.Width = (FLOAT)width; vp.Height = (FLOAT)height; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; g_pImmediateContext->RSSetViewports( 1, &vp ); // Compile the vertex shader ID3DBlob* pVSBlob = NULL; hr = CompileShaderFromFile( L"Tutorial04.fx", "VS", "vs_4_0", &pVSBlob ); if( FAILED( hr ) ) { MessageBox( NULL, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK ); return hr; } // Create the vertex shader hr = g_pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader ); if( FAILED( hr ) ) { pVSBlob->Release(); return hr; } // Define the input layout D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE( layout ); // Create the input layout hr = g_pd3dDevice->CreateInputLayout( layout, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &g_pVertexLayout ); pVSBlob->Release(); if( FAILED( hr ) ) return hr; // Set the input layout g_pImmediateContext->IASetInputLayout( g_pVertexLayout ); // Compile the pixel shader ID3DBlob* pPSBlob = NULL; hr = CompileShaderFromFile( L"Tutorial04.fx", "PS", "ps_4_0", &pPSBlob ); if( FAILED( hr ) ) { MessageBox( NULL, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK ); return hr; } // Create the pixel shader hr = g_pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShader ); pPSBlob->Release(); if( FAILED( hr ) ) return hr; // Create vertex buffer SimpleVertex vertices[] = { { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.0f, 0.0f, 1.0f, 1.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.0f, 1.0f, 0.0f, 1.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 1.0f, 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT4( 1.0f, 0.0f, 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 0.0f, 1.0f, 1.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 0.0f, 1.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.0f, 0.0f, 1.0f, 1.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.0f, 1.0f, 0.0f, 1.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 1.0f, 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT4( 1.0f, 0.0f, 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 0.0f, 1.0f, 1.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 0.0f, 1.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ) }, }; D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof(bd) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( SimpleVertex ) * 8; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA InitData; ZeroMemory( &InitData, sizeof(InitData) ); InitData.pSysMem = vertices; hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer ); if( FAILED( hr ) ) return hr; // Set vertex buffer UINT stride = sizeof( SimpleVertex ); UINT offset = 0; g_pImmediateContext->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &stride, &offset ); // Create index buffer WORD indices[] = { 3,1,0, 2,1,3, 0,5,4, 1,5,0, 3,4,7, 0,4,3, 1,6,5, 2,6,1, 2,7,6, 3,7,2, 6,4,5, 7,4,6, 3,1,0, 2,1,3, 0,5,4, 1,5,0, 3,4,7, 0,4,3, 1,6,5, 2,6,1, 2,7,6, 3,7,2, 6,4,5, 7,4,6, }; bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( WORD ) * 72; // 36 vertices needed for 12 triangles in a triangle list bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; InitData.pSysMem = indices; hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pIndexBuffer ); if( FAILED( hr ) ) return hr; // Set index buffer g_pImmediateContext->IASetIndexBuffer( g_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0 ); // Set primitive topology g_pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); // Create the constant buffer bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(ConstantBuffer); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pConstantBuffer ); if( FAILED( hr ) ) return hr; // Initialize the world matrix for (int i=0; i<50; i++) { g_meshesTransforms[i] = XMMatrixIdentity(); } // Initialize the view matrix XMVECTOR Eye = XMVectorSet( 0.0f, 1.0f, -5.0f, 0.0f ); XMVECTOR At = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ); XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ); g_View = XMMatrixLookAtLH( Eye, At, Up ); // Initialize the projection matrix g_Projection = XMMatrixPerspectiveFovLH( XM_PIDIV2, width / (FLOAT)height, 0.01f, 100.0f ); return S_OK; }
//Makes a Square by default Entity::Entity(int type, std::string label, float width, float height, float depth) : mPosition(0.0f, 0.0f, 0.0f), mShadowScale(0.0f, 0.0f, 0.0f), mRight(1.0f, 0.0f, 0.0f), mUp(0.0f, 1.0f, 0.0f), mLook(0.0f, 0.0f, 1.0f), prevPitch(0.0f), rotationY(0.0f), prevRoll(0.0f), origTexScale(1.0f, 1.0f, 1.0f), texTrans(0.0f, 0.0f, 0.0f), texTransMult(0.0f, 0.0f, 0.0f), mGoToPos(0.0f, 0.0f, 0.0f), currProgress(0.0f), rotationZ(0.0f), mDistanceLeft(0.0f), mTexWidth(0.0f), mTexHeight(0.0f), mUpDown(false), mGrowing(false), mSquishX(false), mSquishY(false), mSquishZ(false), mOrigY(0.0f), mOrigX(0.0f), mOrigZ(0.0f), mGrowOut(false), mHeightToGo(0.0f), mScale(1.0f), mWidth(width), mHeight(height), mDepth(depth), hovering(false), useTexTrans(false), progressBar(false), goToPos(false), billboard(false), flipUpright(false), reverseLook(false), mDead(false), mSpinning(false), mExplode(false), mBasicTexTrans(false), mUseAnimation(false), mUseAAB(false), mUseAABOnce(false), mGoUp(true), mBackFaceCull(true), mGoDown(false), mSideToSide(false), mPulse(false), mOrbit(false), turnAngle(0.0f), explosionDist(0.0f), mAnim(0), movementMult(0.0f), mFlipping(false), mRolling(false), mBackAndForth(false), mGrow(true), mShrink(false), mGrowIn(false), mFlipTexture(false), mTexRotate(false), mLabel(label) { //SET MATERIAL mMat.Ambient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); mMat.Diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); mMat.Specular = XMFLOAT4(1.0f, 1.0f, 1.0f, 48.0f); GeometryGenerator geoGen; //FLOOR PLANE XMMATRIX I = XMMatrixIdentity(); XMStoreFloat4x4(&mWorld, I); XMStoreFloat4x4(&mShadowTrans, I); switch (type) { case 0: geoGen.CreateGrid(width, height, 2, 2, mGrid); break; case 1: geoGen.CreateSphere(width, height, height, mGrid);/*height is slice count .. width for radius*/ break; case 2: geoGen.CreateUprightSquare(width, height, mGrid); break; case 3: geoGen.CreateBox(width, height, depth, mGrid); break; case 4: geoGen.CreateFrontandBackFace(width, height, depth, mGrid); break; case 5: geoGen.CreateCylinder(width, depth, height, 15, 2, mGrid); break; case 6: geoGen.CreateBox2Tex(width, height, depth, mGrid); break; } mIndexCount = mGrid.Indices.size(); mMeshVertices.resize(mGrid.Vertices.size()); }
SpecularLightingDemo::SpecularLightingDemo(Library::Game & game) : DrawableGameComponent(game), mVertexShader(), mIndexCount(), mPixelShader(), mWorldMatrix(MatrixHelper::Identity), mAnimationEnabled(true) { XMStoreFloat4x4(&mWorldMatrix, XMMatrixIdentity()); }
// Draw - must be positioned after all the controls are defined //-------------------------------------------------------------------------------- void CPUTGuiControllerDX11::Draw(ID3D11DeviceContext *pImmediateContext) { HEAPCHECK; if( 0 != GetNumberOfControlsInPanel()) { SetGUIDrawingState(pImmediateContext); } else { return; } ID3D11VertexShader *pVertexShader = mpGUIVertexShader->GetNativeVertexShader(); ID3D11PixelShader *pPixelShader = mpGUIPixelShader->GetNativePixelShader(); // check and see if any of the controls resized themselves int ControlCount=GetNumberOfControlsInPanel(); bool ResizingNeeded = false; for(int ii=0; ii<ControlCount; ii++) { CPUTControl *pControl = mControlPanelIDList[mActiveControlPanelSlotID]->mControlList[ii]; if(true == pControl->ControlResizedItself()) { ResizingNeeded = true; pControl->ControlResizingHandled(); } } // if any of the controls resized, then re-do the autoarrangment if(true == ResizingNeeded) { this->Resize(); } // Now check to see if any controls' graphics are dirty for(int ii=0; ii<ControlCount; ii++) { CPUTControl *pControl = mControlPanelIDList[mActiveControlPanelSlotID]->mControlList[ii]; if(true == pControl->ControlGraphicsDirty()) { mUberBufferDirty = true; break; } } // if any of the controls have announced they are dirty, then rebuild the mirror buffer and update the GFX buffer if(mUberBufferDirty) { // if a resize was flagged, do it now. if(mRecalculateLayout) { RecalculateLayout(); } // 'clear' the buffer by resetting the pointer to the head mUberBufferIndex = 0; mTextUberBufferIndex = 0; mFocusedControlBufferIndex = 0; mFocusedControlTextBufferIndex = 0; int ii=0; while(ii<GetNumberOfControlsInPanel()) { CPUTControl *pControl = mControlPanelIDList[mActiveControlPanelSlotID]->mControlList[ii]; // don't draw the focus control - draw it last so it stays on 'top' if(mpFocusControl != pControl) { switch(pControl->GetType()) { case CPUT_BUTTON: ((CPUTButton*)pControl)->DrawIntoBuffer(mpMirrorBuffer, &mUberBufferIndex, mUberBufferMax, mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_CHECKBOX: ((CPUTCheckbox*)pControl)->DrawIntoBuffer(mpMirrorBuffer, &mUberBufferIndex, mUberBufferMax, mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_SLIDER: ((CPUTSlider*)pControl)->DrawIntoBuffer(mpMirrorBuffer, &mUberBufferIndex, mUberBufferMax, mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_DROPDOWN: ((CPUTDropdown*)pControl)->DrawIntoBuffer(mpMirrorBuffer, &mUberBufferIndex, mUberBufferMax, mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_STATIC: ((CPUTText*)pControl)->DrawIntoBuffer(mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; } } ii++; HEAPCHECK } // do the 'focused' control last so it stays on top (i.e. dropdowns) if(mpFocusControl) { switch(mpFocusControl->GetType()) { case CPUT_BUTTON: ((CPUTButton*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlBufferIndex, mUberBufferMax, mpFocusedControlTextMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_CHECKBOX: ((CPUTCheckbox*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlBufferIndex, mUberBufferMax, mpFocusedControlTextMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_SLIDER: ((CPUTSlider*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlBufferIndex, mUberBufferMax, mpFocusedControlTextMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_DROPDOWN: ((CPUTDropdown*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlBufferIndex, mUberBufferMax, mpFocusedControlTextMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_STATIC: ((CPUTText*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; } } // update the uber-buffers with the control graphics UpdateUberBuffers(pImmediateContext); // Clear dirty flag on uberbuffer mUberBufferDirty = false; } HEAPCHECK // calculate the fps double elapsed = mpFPSTimer->GetElapsedTime(); double fps = 1.0 / elapsed; mLastFPS = (float) fps; // if we're drawing the FPS counter - update that // We do this independently of uber-buffer updates since we'll have FPS updates every frame, // but likely not have control updates every frame if(mbDrawFPS) { // calculate the time elapsed since last frame bool UberBufferWasDirty = mUberBufferDirty; cString Data; { wchar_t wcstring[CPUT_MAX_STRING_LENGTH]; swprintf_s(&wcstring[0], CPUT_MAX_STRING_LENGTH, _L("%.2f"), fps); Data=wcstring; } // build the FPS string cString FPS = _L("FPS: ")+Data; mpFPSCounter->SetText(FPS); // 'draw' the string into the buffer mFPSBufferIndex = 0; mpFPSCounter->DrawIntoBuffer(mpFPSMirrorBuffer, &mFPSBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); // update the DirectX vertex buffer ASSERT(CPUT_GUI_BUFFER_STRING_SIZE > mFocusedControlTextBufferIndex, _L("CPUT GUI: Too many strings for default-sized uber-buffer. Increase CPUT_GUI_BUFFER_STRING_SIZE")); pImmediateContext->UpdateSubresource(mpFPSDirectXBuffer, 0, NULL, mpFPSMirrorBuffer, mFPSBufferIndex*sizeof(CPUTGUIVertex), 0); // start next frame timer mpFPSTimer->StartTimer(); if(false == UberBufferWasDirty) { mUberBufferDirty = false; } } // set up orthographic display int windowWidth, windowHeight; GUIConstantBufferVS ConstantBufferMatrices; float znear = 0.1f; float zfar = 100.0f; XMMATRIX m; CPUTOSServices *pServices = CPUTOSServices::GetOSServices(); pServices->GetClientDimensions( &windowWidth, &windowHeight ); m = XMMatrixOrthographicOffCenterLH(0, (float)windowWidth, (float)windowHeight, 0, znear, zfar); ConstantBufferMatrices.Projection = XMMatrixTranspose( m ); // set the vertex shader pImmediateContext->VSSetShader( pVertexShader, NULL, 0 ); UINT VertexStride = sizeof(CPUTGUIVertex); UINT VertexOffset = 0; pImmediateContext->IASetVertexBuffers( 0, 1, &mpUberBuffer, &VertexStride, &VertexOffset ); m = XMMatrixIdentity(); ConstantBufferMatrices.Model = XMMatrixTranspose( m ); pImmediateContext->UpdateSubresource( mpConstantBufferVS, 0, NULL, &ConstantBufferMatrices, 0, 0 ); pImmediateContext->VSSetConstantBuffers( 0, 1, &mpConstantBufferVS ); // -- draw the normal controls -- // draw the control graphics pImmediateContext->PSSetShader( pPixelShader, NULL, 0 ); pImmediateContext->PSSetShaderResources( 0, 1, &mpControlTextureAtlasView ); pImmediateContext->Draw(mUberBufferIndex,0); // draw the control's text pImmediateContext->PSSetShaderResources( 0, 1, &mpTextTextureAtlasView ); pImmediateContext->IASetVertexBuffers( 0, 1, &mpTextUberBuffer, &VertexStride, &VertexOffset ); // draw the text uber-buffer pImmediateContext->Draw(mTextUberBufferIndex,0); // draw the FPS counter if(mbDrawFPS) { pImmediateContext->IASetVertexBuffers( 0, 1, &mpFPSDirectXBuffer, &VertexStride, &VertexOffset ); pImmediateContext->Draw(mFPSBufferIndex, 0); } // -- draw the focused control -- // Draw the focused control's graphics pImmediateContext->PSSetShader( pPixelShader, NULL, 0 ); pImmediateContext->PSSetShaderResources( 0, 1, &mpControlTextureAtlasView ); pImmediateContext->IASetVertexBuffers( 0, 1, &mpFocusedControlBuffer, &VertexStride, &VertexOffset ); // draw the uber-buffer pImmediateContext->Draw(mFocusedControlBufferIndex,0); // Draw the focused control's text pImmediateContext->PSSetShaderResources( 0, 1, &mpTextTextureAtlasView ); pImmediateContext->IASetVertexBuffers( 0, 1, &mpFocusedControlTextBuffer, &VertexStride, &VertexOffset ); // draw the text uber-buffer pImmediateContext->Draw(mFocusedControlTextBufferIndex,0); // restore the drawing state ClearGUIDrawingState(pImmediateContext); HEAPCHECK; }
void LevelDisplay::draw( ID3D11DeviceContext* device, ID3DX11Effect* fx, World& world, XMFLOAT4& cameraPos, float blockDimensions ) { UINT stride = sizeof(DungeonVertex); UINT offset = 0; //Update the world matrix XMMATRIX worldm = XMMatrixIdentity(); //Set input layout and topology device->IASetInputLayout( mInputLayout ); device->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); //Update the world matrix device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); device->VSSetConstantBuffers( 1, 1, &mWorldCB ); //Set the floor texture device->PSSetShaderResources(0, 1, &mFloorTexture ); //Draw the floor device->IASetIndexBuffer( mFloorIB, DXGI_FORMAT_R16_UINT, 0 ); device->IASetVertexBuffers(0, 1, &mFloorVB, &stride, &offset); device->DrawIndexed(6 * mBlockCount, 0, 0); //Draw the walls device->PSSetShaderResources(0, 1, &mWallTexture ); device->IASetIndexBuffer( mWallsIB, DXGI_FORMAT_R16_UINT, 0 ); device->IASetVertexBuffers(0, 1, &mWallsVB, &stride, &offset); device->DrawIndexed(6 * mWallCount, 0, 0); //Draw the ceiling device->PSSetShaderResources(0, 1, &mCeilingTexture ); device->IASetIndexBuffer( mCeilingIB, DXGI_FORMAT_R16_UINT, 0 ); device->IASetVertexBuffers(0, 1, &mCeilingVB, &stride, &offset); device->DrawIndexed(6 * mBlockCount, 0, 0); Level& level = world.getLevel(); float halfBlockDimension = blockDimensions / 2.0f; //Draw light meshes at light locations for(ushort i = 0; i < level.getNumLights(); i++){ Level::Light& l = level.getLight( i ); float xOffset = 0.0f; float zOffset = 0.0f; if( l.getType() == Level::Light::Type::Torch ){ xOffset = l.getAttachedWall() == Level::Light::AttachedWall::Left ? -halfBlockDimension : ( l.getAttachedWall() == Level::Light::AttachedWall::Back ? halfBlockDimension : 0.0f ); zOffset = l.getAttachedWall() == Level::Light::AttachedWall::Right ? halfBlockDimension : ( l.getAttachedWall() == Level::Light::AttachedWall::Front ? -halfBlockDimension : 0.0f ); } float tx = ( static_cast<float>(l.getI()) * blockDimensions ) + halfBlockDimension + xOffset; float ty = l.getHeight(); float tz = ( static_cast<float>(l.getJ()) * blockDimensions ) + halfBlockDimension + zOffset; float dx = (cameraPos.x - tx); float dz = (cameraPos.z - tz); float d = sqrt( (dx * dx) + (dz * dz) ); //If we are outside the draw range, skip drawing this one if( d > mDrawRange ){ continue; } worldm = XMMatrixScaling( mLightScale[ l.getType() ], mLightScale[ l.getType() ], mLightScale[ l.getType() ] ) * XMMatrixRotationY( static_cast<float>( l.getAttachedWall() ) * PI_OVER_2 ) * XMMatrixTranslation( tx, ty, tz ); worldm = XMMatrixTranspose( worldm ); device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); device->VSSetConstantBuffers( 1, 1, &mWorldCB ); mLights[ l.getType() - 1 ].draw( device ); } //Draw furniture meshes for(uint i = 0; i < level.getNumFurniture(); i++) { Level::Furniture& f = level.getFurniture(i); float dx = (cameraPos.x - f.getPosition().x); float dz = (cameraPos.z - f.getPosition().z); float d = sqrt( (dx * dx) + (dz * dz) ); //If we are outside the draw range, skip drawing this one if( d > mDrawRange ){ continue; } worldm = XMMatrixScaling( mFurnitureScale[ f.getType() ], mFurnitureScale[ f.getType() ], mFurnitureScale[ f.getType() ]) * XMMatrixRotationY( f.getYRotation() ) * XMMatrixTranslation( f.getPosition().x, f.getPosition().y, f.getPosition().z ); worldm = XMMatrixTranspose( worldm ); device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); device->VSSetConstantBuffers( 1, 1, &mWorldCB ); mFurniture[ f.getType() - 1 ].draw(device); } //Draw Containers for(uint i = 0; i < level.getNumContainer(); i++) { Level::Container& f = level.getContainer(i); float dx = (cameraPos.x - f.getPosition().x); float dz = (cameraPos.z - f.getPosition().z); float d = sqrt( (dx * dx) + (dz * dz) ); //If we are outside the draw range, skip drawing this one if( d > mDrawRange ){ continue; } worldm = XMMatrixScaling( mContainerScale[ f.getCType() ], mContainerScale[ f.getCType() ], mContainerScale[ f.getCType() ]) * XMMatrixRotationY( f.getYRotation() ) * XMMatrixTranslation( f.getPosition().x, f.getPosition().y, f.getPosition().z ); worldm = XMMatrixTranspose( worldm ); device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); device->VSSetConstantBuffers( 1, 1, &mWorldCB ); mContainers[ f.getCType() - 1 ].draw(device); } for(uint i = 0; i < level.getNumDoors(); i++) { Level::Door& f = level.getDoor(i); float dx = (cameraPos.x - f.getPosition().x); float dz = (cameraPos.z - f.getPosition().z); float d = sqrt( (dx * dx) + (dz * dz) ); //If we are outside the draw range, skip drawing this one if( d > mDrawRange ){ continue; } worldm = XMMatrixScaling( mDoorScale, mDoorScale, mDoorScale) * XMMatrixRotationY( f.getYRotation() ) * XMMatrixTranslation( f.getPosition().x, f.getPosition().y, f.getPosition().z ); worldm = XMMatrixTranspose( worldm ); device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); device->VSSetConstantBuffers( 1, 1, &mWorldCB ); mDoor.draw(device); } }
void TransparencyDemo::UpdateDirectionalLight(const GameTime& gameTime) { static float directionalIntensity = 1.0f; float elapsedTime = static_cast<float>(gameTime.ElapsedGameTime().count()) / 1000.0f; Library::GamePadComponent* gp = mGame->GetGamePad(); // Update directional light intensity if (gp->IsButtonDown(GamePadButton::Y) && directionalIntensity < 1.0f) { directionalIntensity += elapsedTime; directionalIntensity = min(directionalIntensity, 1.0f); mPixelCBufferPerFrameData.LightColor = XMFLOAT4(directionalIntensity, directionalIntensity, directionalIntensity, 1.0f); mDirectionalLight->SetColor(mPixelCBufferPerFrameData.LightColor); } if (gp->IsButtonDown(GamePadButton::X) && directionalIntensity > 0.0f) { directionalIntensity -= elapsedTime; directionalIntensity = max(directionalIntensity, 0.0f); mPixelCBufferPerFrameData.LightColor = XMFLOAT4(directionalIntensity, directionalIntensity, directionalIntensity, 1.0f); mDirectionalLight->SetColor(mPixelCBufferPerFrameData.LightColor); } // Rotate directional light XMFLOAT2 rotationAmount = Vector2Helper::Zero; if (gp->CurrentState().IsLeftThumbStickRight()) { rotationAmount.x += LightRotationRate.x * elapsedTime; } if (gp->CurrentState().IsLeftThumbStickLeft()) { rotationAmount.x -= LightRotationRate.x * elapsedTime; } if (gp->CurrentState().IsLeftThumbStickUp()) { rotationAmount.y += LightRotationRate.y * elapsedTime; } if (gp->CurrentState().IsLeftThumbStickDown()) { rotationAmount.y -= LightRotationRate.y * elapsedTime; } XMMATRIX lightRotationMatrix = XMMatrixIdentity(); if (rotationAmount.x != 0) { lightRotationMatrix = XMMatrixRotationY(rotationAmount.x); } if (rotationAmount.y != 0) { XMMATRIX lightRotationAxisMatrix = XMMatrixRotationAxis(mDirectionalLight->RightVector(), rotationAmount.y); lightRotationMatrix *= lightRotationAxisMatrix; } if (rotationAmount.x != 0.0f || rotationAmount.y != 0.0f) { mDirectionalLight->ApplyRotation(lightRotationMatrix); mProxyModel->ApplyRotation(lightRotationMatrix); const XMFLOAT3& lightdirection = mDirectionalLight->Direction(); mVertexCBufferPerFrameData.LightDirection = XMFLOAT4(lightdirection.x, lightdirection.y, lightdirection.z, 0.0f); } }
// ジオメトリの初期化 HRESULT InitGeometry( void ) { HRESULT hr = S_OK; // 頂点バッファ作成 D3D11_BUFFER_DESC BufferDesc; BufferDesc.Usage = D3D11_USAGE_DYNAMIC; BufferDesc.ByteWidth = sizeof( CUSTOMVERTEX ) * MAX_BUFFER_VERTEX; BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; BufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA SubResourceData; SubResourceData.pSysMem = g_cvVertices; SubResourceData.SysMemPitch = 0; SubResourceData.SysMemSlicePitch = 0; hr = g_pd3dDevice->CreateBuffer( &BufferDesc, &SubResourceData, &g_pVertexBuffer ); if ( FAILED( hr ) ) { return hr; } // インデックスバッファ作成 BufferDesc.Usage = D3D11_USAGE_DYNAMIC; BufferDesc.ByteWidth = sizeof( WORD ) * MAX_BUFFER_INDEX; BufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; BufferDesc.MiscFlags = 0; SubResourceData.pSysMem = g_wIndices; hr = g_pd3dDevice->CreateBuffer( &BufferDesc, &SubResourceData, &g_pIndexBuffer ); if( FAILED( hr ) ) return hr; // テクスチャ作成 g_tGroundTexture.pSRViewTexture = NULL; hr = LoadTexture( _T( "10.bmp" ), &g_tGroundTexture, 691, 691, 1024, 1024 ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't open 10.bmp" ), _T( "Error" ), MB_OK ); return hr; } g_tAreaTexture.pSRViewTexture = NULL; hr = LoadTexture( _T( "8.bmp" ), &g_tAreaTexture, 185, 185, 256, 256 ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't open 8.bmp" ), _T( "Error" ), MB_OK ); return hr; } g_tPlayerTexture.pSRViewTexture = NULL; hr = LoadTexture( _T( "9.bmp" ), &g_tPlayerTexture, 222, 222, 256, 256 ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't open 9.bmp" ), _T( "Error" ), MB_OK ); return hr; } // モデル作成 int nVertexNum1, nIndexNum1; int nVertexNum2, nIndexNum2; // プレイヤー MakeSphereIndexed( 0.0f, 0.68f, 0.0f, 0.16f, &( g_cvVertices[g_nVertexNum] ), &nVertexNum1, &( g_wIndices[g_nIndexNum] ), &nIndexNum1, 0 ); MakeConeIndexed( 0.5f, 0.2f, &( g_cvVertices[g_nVertexNum + nVertexNum1] ), &nVertexNum2, &( g_wIndices[g_nIndexNum + nIndexNum1] ), &nIndexNum2, nVertexNum1 ); g_mmPlayer.nVertexPos = g_nVertexNum; g_mmPlayer.nVertexNum = nVertexNum1 + nVertexNum2; g_mmPlayer.nIndexPos = g_nIndexNum; g_mmPlayer.nIndexNum = nIndexNum1 + nIndexNum2; g_nVertexNum += nVertexNum1 + nVertexNum2; g_nIndexNum += nIndexNum1 + nIndexNum2; g_mmPlayer.ptpTexture = &g_tPlayerTexture; g_mmPlayer.mMatrix = XMMatrixIdentity(); g_mmPlayer.v4AddColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); // 地面 g_cvVertices[g_nVertexNum ].v4Pos = XMFLOAT4( -GROUND_SIZE / 2, 0.0f, GROUND_SIZE / 2, 1.0f ); g_cvVertices[g_nVertexNum ].v2UV = XMFLOAT2( 0.0f, 0.0f ); g_cvVertices[g_nVertexNum + 1].v4Pos = XMFLOAT4( GROUND_SIZE / 2, 0.0f, GROUND_SIZE / 2, 1.0f ); g_cvVertices[g_nVertexNum + 1].v2UV = XMFLOAT2( 1.0f, 0.0f ); g_cvVertices[g_nVertexNum + 2].v4Pos = XMFLOAT4( -GROUND_SIZE / 2, 0.0f, -GROUND_SIZE / 2, 1.0f ); g_cvVertices[g_nVertexNum + 2].v2UV = XMFLOAT2( 0.0f, 1.0f ); g_cvVertices[g_nVertexNum + 3].v4Pos = XMFLOAT4( GROUND_SIZE / 2, 0.0f, -GROUND_SIZE / 2, 1.0f ); g_cvVertices[g_nVertexNum + 3].v2UV = XMFLOAT2( 1.0f, 1.0f ); g_wIndices[g_nIndexNum ] = 0; g_wIndices[g_nIndexNum + 1] = 2; g_wIndices[g_nIndexNum + 2] = 1; g_wIndices[g_nIndexNum + 3] = 1; g_wIndices[g_nIndexNum + 4] = 2; g_wIndices[g_nIndexNum + 5] = 3; g_mmGround.nVertexPos = g_nVertexNum; g_mmGround.nVertexNum = 4; g_mmGround.nIndexPos = g_nIndexNum; g_mmGround.nIndexNum = 6; g_nVertexNum += 4; g_nIndexNum += 6; g_mmGround.ptpTexture = &g_tGroundTexture; g_mmGround.mMatrix = XMMatrixIdentity(); g_mmGround.v4AddColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); // 当たり判定多角形 int i; float fAngle = 0.0f; float fDeltaAng = 2.0f * PI / CHECK_POLYGON_ANGLES; float fRadius; float x, y, z; g_cvVertices[g_nVertexNum ].v4Pos = XMFLOAT4( g_HitPolygonCenter.x, 0.0f, g_HitPolygonCenter.z, 1.0f ); g_cvVertices[g_nVertexNum ].v2UV = XMFLOAT2( 0.0f, 0.0f ); nVertexNum1 = 1; for ( i = 0; i < CHECK_POLYGON_ANGLES + 1; i++ ) { fRadius = 2.0f * ( cosf( fAngle * 3.0f ) + 1.7f ); x = g_HitPolygonCenter.x + fRadius * cosf( fAngle ); y = 0.01f; z = g_HitPolygonCenter.z + fRadius * sinf( fAngle ); g_HitPolygonVertices[i] = XMFLOAT3( x, y, z ); g_cvVertices[g_nVertexNum + nVertexNum1].v4Pos = XMFLOAT4( x, y, z, 1.0f ); g_cvVertices[g_nVertexNum + nVertexNum1].v2UV = XMFLOAT2( ( float )i / CHECK_POLYGON_ANGLES, 1.0f ); nVertexNum1++; fAngle += fDeltaAng; } nIndexNum1 = 0; for ( i = 0; i < CHECK_POLYGON_ANGLES; i++ ) { g_wIndices[g_nIndexNum + nIndexNum1 ] = 0; g_wIndices[g_nIndexNum + nIndexNum1 + 1] = i + 1; g_wIndices[g_nIndexNum + nIndexNum1 + 2] = i + 2; nIndexNum1 += 3; } g_mmHitPolygon.nVertexPos = g_nVertexNum; g_mmHitPolygon.nVertexNum = nVertexNum1; g_mmHitPolygon.nIndexPos = g_nIndexNum; g_mmHitPolygon.nIndexNum = nIndexNum1; g_nVertexNum += nVertexNum1; g_nIndexNum += nIndexNum1; g_mmHitPolygon.ptpTexture = &g_tAreaTexture; g_mmHitPolygon.mMatrix = XMMatrixIdentity(); g_mmHitPolygon.v4AddColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); // 頂点バッファ・インデックスバッファ作成 D3D11_MAPPED_SUBRESOURCE mappedVertices, mappedIndices; hr = g_pImmediateContext->Map( g_pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedVertices ); if( FAILED( hr ) ) return hr; hr = g_pImmediateContext->Map( g_pIndexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedIndices ); if( FAILED( hr ) ) { g_pImmediateContext->Unmap( g_pVertexBuffer, 0 ); return hr; } CopyMemory( mappedVertices.pData, g_cvVertices, sizeof( CUSTOMVERTEX ) * g_nVertexNum ); CopyMemory( mappedIndices.pData, g_wIndices, sizeof( WORD ) * g_nIndexNum ); g_pImmediateContext->Unmap( g_pVertexBuffer, 0 ); g_pImmediateContext->Unmap( g_pIndexBuffer, 0 ); return S_OK; }
void glLoadIdentity(void) { CURRENT_MATRIX_STACK = XMMatrixIdentity(); current_matrix->dirty = 1; }
bool D3DAnimation::Init() { if (!D3DBase::Init()) { return false; } mLastMousePos.x = 0; mLastMousePos.y = 0; BOX_DESC box = {1.0f, 1.0f, 1.0f, 3}; GRID_DESC grid = {20.0f, 30.0f, 60, 40}; SPHERE_DESC sphere = {0.5f, 20, 20}; CYLINDER_DESC cylinder = { 0.5f, 0.3f, 3.0f, 20, 20 }; Material mGridMat; Material mBoxMat; Material mCylinderMat; Material mSphereMat; mGridMat.Ambient = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f); mGridMat.Diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f); mGridMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f); mCylinderMat.Ambient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); mCylinderMat.Diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); mCylinderMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f); mSphereMat.Ambient = XMFLOAT4(0.6f, 0.8f, 0.9f, 1.0f); mSphereMat.Diffuse = XMFLOAT4(0.6f, 0.8f, 0.9f, 1.0f); mSphereMat.Specular = XMFLOAT4(0.9f, 0.9f, 0.9f, 16.0f); mBoxMat.Ambient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); mBoxMat.Diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); mBoxMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f); fogenable = true; XMFLOAT4X4 I; XMFLOAT4X4 rotation; XMStoreFloat4x4(&rotation, XMMatrixRotationY(XM_PI)); XMStoreFloat4x4(&I, XMMatrixIdentity()); //instanceName;translation;rotation;scale;modelName;modelFilename;texturePath;VShaderName;PShaderName;LayoutName; vertexTypeName; std::vector<ObjectInstance_M3dModelList_DESC> objlist = { {"player", {0.0f, 0.0f, -100.0f}, rotation, {0.05f, 0.05f, -0.05f}, "soldier", ".\\Models\\soldier.m3d", ".\\Textures\\","BasicAnimationVS","FixFunctionLightPS","PosNormalTexTanSkinned","PosNormalTexTanAnimation"} }; std::vector<ObjectInstance_BOXLIST_DESC> boxlist = { { "podium",{0.0f, 0.5f, 0.0f}, I, {3.0f,1.0f,3.0f}, "box", mBoxMat, ".\\Textures\\", "stone.dds", "stones_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",box} }; std::vector<ObjectInstance_GRIDLIST_DESC> gridlist = { { "land", {0.0f, 0.0f,0.0f}, I, {1.0f,1.0f,1.0f}, "grid", mGridMat, ".\\Textures\\", "floor.dds", "floor_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",grid} }; mDirLights[0].Ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); mDirLights[0].Diffuse = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); mDirLights[0].Specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); mDirLights[0].Direction = XMFLOAT3(0.57735f, -0.57735f, 0.57735f); dirLightsw[0] = true; mDirLights[1].Ambient = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f); mDirLights[1].Diffuse = XMFLOAT4(0.20f, 0.20f, 0.20f, 1.0f); mDirLights[1].Specular = XMFLOAT4(0.25f, 0.25f, 0.25f, 1.0f); mDirLights[1].Direction = XMFLOAT3(-0.57735f, -0.57735f, 0.57735f); dirLightsw[1] = true; mDirLights[2].Ambient = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f); mDirLights[2].Diffuse = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); mDirLights[2].Specular = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f); mDirLights[2].Direction = XMFLOAT3(0.0f, -0.707f, -0.707f); dirLightsw[2] = true; mSpotLights[0].Ambient = XMFLOAT4(0.2f, 1.0f, 0.2f, 1.0f); mSpotLights[0].Diffuse = XMFLOAT4(0.5f, 1.0f, 0.5f, 1.0f); mSpotLights[0].Specular = XMFLOAT4(0.5f, 1.0f, 0.5f, 1.0f); mSpotLights[0].Position = XMFLOAT3(0.0f, 5.0f, 0.0f); mSpotLights[0].Range = 25.0f; mSpotLights[0].Att = XMFLOAT3(0.0f, 0.15f, 0.0f); XMFLOAT3 dir; XMStoreFloat3(&dir, XMVector3Normalize(XMLoadFloat3(&XMFLOAT3(0.0f, -5.0f, -100.0f)))); mSpotLights[0].Direction = dir; mSpotLights[0].Spot = 56.0f; SpotLightsw[0] = true; mSpotLights[1].Ambient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); mSpotLights[1].Diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); mSpotLights[1].Specular = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); mSpotLights[1].Position = XMFLOAT3(0.0f, 2.5f, -100.0f); mSpotLights[1].Range = 15.0f; mSpotLights[1].Att = XMFLOAT3(0.0f, 0.15f, 0.0f); mSpotLights[1].Direction = XMFLOAT3(0.0f, 0.0f, -1.0f); mSpotLights[1].Spot = 50.0f; SpotLightsw[1] = true; std::vector<ObjectInstance_SPHERELIST_DESC> spherelist; std::vector<ObjectInstance_CYLINDERLIST_DESC> cylinderlist; for(int i = 0; i < 5; ++i) { ObjectInstance_CYLINDERLIST_DESC item1 = { "pillar" + std::to_string(i * 2 + 1), {-5.0f, 1.5f, -10.0f + i*5.0f}, I, {1.0f,1.0f,1.0f}, "cylinder", mCylinderMat, ".\\Textures\\", "bricks.dds", "bricks_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan", cylinder}; ObjectInstance_CYLINDERLIST_DESC item2 = { "pillar" + std::to_string(i * 2 + 2), {+5.0f, 1.5f, -10.0f + i*5.0f}, I, {1.0f,1.0f,1.0f}, "cylinder", mCylinderMat, ".\\Textures\\", "bricks.dds", "bricks_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",cylinder}; cylinderlist.push_back(item1); cylinderlist.push_back(item2); ObjectInstance_SPHERELIST_DESC item3 = { "ball" + std::to_string(i * 2 + 1), {-5.0f, 3.5f, -10.0f + i*5.0f}, I, {1.0f,1.0f,1.0f}, "sphere", mCylinderMat, ".\\Textures\\", "stone.dds", "stones_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",sphere}; ObjectInstance_SPHERELIST_DESC item4 = { "ball" + std::to_string(i * 2 + 2), {+5.0f, 3.5f, -10.0f + i*5.0f}, I, {1.0f,1.0f,1.0f}, "sphere", mCylinderMat, ".\\Textures\\", "stone.dds", "stones_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",sphere}; spherelist.push_back(item3); spherelist.push_back(item4); mPointLights[i * 2].Ambient = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f); mPointLights[i * 2].Diffuse = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f); mPointLights[i * 2].Specular = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f); mPointLights[i * 2].Position = XMFLOAT3(-5.0f, 3.5f, -10.0f + i * 5.0f); mPointLights[i * 2].Att = XMFLOAT3(0.0f, 0.0f, 0.9f); mPointLights[i * 2].Range = 4.0f; pointLightsw[i * 2] = true; mPointLights[i * 2 + 1].Ambient = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f); mPointLights[i * 2 + 1].Diffuse = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f); mPointLights[i * 2 + 1].Specular = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f); mPointLights[i * 2 + 1].Position = XMFLOAT3(+5.0f, 3.5f, -10.0f + i * 5.0f); mPointLights[i * 2 + 1].Att = XMFLOAT3(0.0f, 0.9f, 0.0f); mPointLights[i * 2 + 1].Range = 4.0f; pointLightsw[i * 2 + 1] = true; } list = new Object3DList(this,objlist); list->AddBoxist(boxlist); list->AddGridList(gridlist); list->AddCylinderList(cylinderlist); list->AddSphereList(spherelist); list->Init(); Cam.SetLens(0.25f * XM_PI, getAspectRatio(), 1.0f, 1000.0f); return true; }
//================================================================================================================= bool TopdownTile::Render(Camera* camera, float blendAmount, XMFLOAT2 offset) { //Render the regular texture below a fog texture that needs transparency /*if (m_fogBit != fow_n_non && m_fogBit != fow_n_all && m_bFOW)// || bFowUncovered) { ZShadeSandboxMesh::MeshRenderParameters mrp; mrp.camera = camera; mrp.blendAmount = blendAmount; mrp.specifyWorld = true; mrp.world = XMMatrixIdentity(); if (m_CurrentSequence == NULL) { if (mBaseMesh == NULL) return false; mBaseMesh->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); mBaseMesh->Render(mrp); } else { // If the tile has animation render it under the FOW tile RenderAnimation(camera, blendAmount, offset); } // Renders a transparent FOW tile above the regular tile RenderFow(camera, blendAmount, offset); //if (mMesh == NULL) return false; //mMesh->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); //mMesh->Render(mrp); } else if (m_fogBit == fow_n_all && m_bFOW) { ZShadeSandboxMesh::MeshRenderParameters mrp; mrp.camera = camera; mrp.blendAmount = blendAmount; mrp.specifyWorld = true; mrp.world = XMMatrixIdentity(); if (fow_all_texture == NULL) return false; fow_all_texture->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); fow_all_texture->Render(mrp); } else { if (m_CurrentSequence == NULL) { if (mBaseMesh == NULL) return false; mBaseMesh->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); ZShadeSandboxMesh::MeshRenderParameters mrp; mrp.camera = camera; mrp.blendAmount = blendAmount; mrp.specifyWorld = true; mrp.world = XMMatrixIdentity(); mBaseMesh->Render(mrp); } else { //Render TopdownTile Animation2D RenderAnimation(camera, blendAmount, offset); } } if (m_displayHardbox && mHard) RenderHardboxMesh(camera, offset);*/ if (m_CurrentSequence == NULL) { if (mBaseMesh == NULL) return false; mBaseMesh->UpdateBuffers(m_TopLeftPosition.x + offset.x, m_TopLeftPosition.y + offset.y); ZShadeSandboxMesh::MeshRenderParameters mrp; mrp.camera = camera; mrp.blendAmount = blendAmount; mrp.specifyWorld = true; mrp.world = XMMatrixIdentity(); mBaseMesh->Render(mrp); } else { //Render TopdownTile Animation2D RenderAnimation(camera, blendAmount, offset); } if (m_displayHardbox && mHard) RenderHardboxMesh(camera, offset); return true; }
void InClassProj::DrawScene() { md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::White)); md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0); md3dImmediateContext->IASetInputLayout(Vertex::GetNormalTexVertLayout()); md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); XMVECTOR ambient = XMLoadFloat4(&mAmbientColour); XMVECTOR eyePos = XMVectorSet(m2DCam->GetPos().m128_f32[0], m2DCam->GetPos().m128_f32[1], m2DCam->GetPos().m128_f32[2], 0.0f); XMMATRIX proj = XMLoadFloat4x4(&mProj); XMMATRIX view = m2DCam->GetView(); mLitTexEffect->SetPerFrameParams(ambient, eyePos, mPointLight, mSpotLight); XMMATRIX vp = view * proj; vp = XMMatrixIdentity(); proj = XMLoadFloat4x4(&m2DProj); view = m2DCam->GetView(); vp = vp * view * proj; md3dImmediateContext->IASetInputLayout(Vertex::GetNormalTexVertLayout()); md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; md3dImmediateContext->OMSetBlendState(mTransparentBS, blendFactor, 0xffffffff); md3dImmediateContext->OMSetDepthStencilState(mFontDS, 0); vp = XMMatrixIdentity(); proj = XMLoadFloat4x4(&m2DProj); view = m2DCam->GetView(); vp = vp * view * proj; mBG->Draw(vp, md3dImmediateContext, mLitTexEffect); //draw player if (isFacingRight) { mPlayer->SetScale(XMVectorSet(1.0f, 1.0f, 0.0f, 0.0f)); } else if (!isFacingRight) { mPlayer->SetScale(XMVectorSet(-1.0f, 1.0f, 0.0f, 0.0f)); } mPlayer->Draw(vp, md3dImmediateContext, mLitTexEffect); md3dImmediateContext->RSSetState(0); //draw enemies for (int i = 0; i < enemies.size(); ++i) { enemies[i]->Draw(vp, md3dImmediateContext, mLitTexEffect); //draw enemy health bars greenBarVec[i]->Draw(vp, md3dImmediateContext, mLitTexEffect); redBarVec[i]->Draw(vp, md3dImmediateContext, mLitTexEffect); } //draw arrow projectiles for (int i = 0; i < mProjectiles.size(); ++i) { mProjectiles[i]->Draw(vp, md3dImmediateContext, mLitTexEffect); } //draw end of level object if (EOLobjActive) { EOLobj->Draw(vp, md3dImmediateContext, mLitTexEffect); //EOLobj->Play(true); } DrawParticles(); md3dImmediateContext->OMSetDepthStencilState(0, 0); md3dImmediateContext->OMSetBlendState(0, blendFactor, 0xffffffff); //mFont->DrawFont(md3dImmediateContext, XMVectorSet(10.0f, 500.0f, 0.0f, 0.0f), 50, 75, 10, "Hi Brandon, you are a good student"); HR(mSwapChain->Present(1, 0)); }
void S3DViewPanel::UpdateCamera(wxMouseEvent& event) { static wxPoint point; if( event.LeftDown() || event.RightDown() || event.MiddleDown() ) point = event.GetPosition(); if( event.LeftIsDown() || event.RightIsDown() || event.MiddleIsDown() ) { long x = event.GetX(); long y = event.GetY(); CVector2 dPoint = CVector2( point.x - x, point.y - y); point.x = x; point.y = y; IEntity* pCamera = GLOBAL::ObserverCamera()->GetEntity(); if( event.LeftIsDown() ) { if( GLOBAL::SelectionMgr()->List()->size() == 0 ) { // FPS camera moving if( fabs(dPoint.x) > fabs(dPoint.y) ) pCamera->RotateLocalAxis( CVector3(0, 0, 1), dPoint.x * 0.005f); else pCamera->RotateLocalAxis( pCamera->GetWorldTM().r[0], dPoint.y * 0.005f ); } else { // rotate in entity coordinate system IEntity* pEntity = GLOBAL::SelectionMgr()->First(); XMMATRIX entityTM = XMMatrixIdentity(); entityTM.r[3] = pEntity->GetWorldPos().ToXMVEECTOR(); XMMATRIX invEntityTM = XMMATRIX_UTIL::Inverse(NULL, entityTM ); XMMATRIX tm = XMMatrixMultiply( pCamera->GetWorldTM() , invEntityTM ); if( fabs(dPoint.x) > fabs(dPoint.y) ) { XMMATRIX rotTM = XMMatrixRotationAxis( CVector3(0,0,1).ToXMVEECTOR(), dPoint.x * 0.005f ); tm = XMMatrixMultiply( tm, rotTM ); } else { XMMATRIX rotTM = XMMatrixRotationAxis( pCamera->GetWorldTM().r[0] ,dPoint.y * 0.005f); tm = XMMatrixMultiply( tm, rotTM ); } tm = XMMatrixMultiply( tm, entityTM ); pCamera->SetWorldTM( tm ); } } else if( event.RightIsDown() ) { pCamera->MoveOnLocalAxis( 0 , 0, dPoint.y * m_CameraSpeed ); } else if( event.MiddleIsDown() ) { pCamera->MoveOnLocalAxis( -dPoint.x * m_CameraSpeed , dPoint.y * m_CameraSpeed, 0 ); } } }
void MirrorApp::DrawScene() { md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::Black)); md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0); md3dImmediateContext->IASetInputLayout(InputLayouts::Basic32); md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); float blendFactor[] = {0.0f, 0.0f, 0.0f, 0.0f}; UINT stride = sizeof(Vertex::Basic32); UINT offset = 0; XMMATRIX view = XMLoadFloat4x4(&mView); XMMATRIX proj = XMLoadFloat4x4(&mProj); XMMATRIX viewProj = view*proj; // Set per frame constants. Effects::BasicFX->SetDirLights(mDirLights); Effects::BasicFX->SetEyePosW(mEyePosW); Effects::BasicFX->SetFogColor(Colors::Black); Effects::BasicFX->SetFogStart(2.0f); Effects::BasicFX->SetFogRange(40.0f); // Skull doesn't have texture coordinates, so we can't texture it. ID3DX11EffectTechnique* activeTech; ID3DX11EffectTechnique* activeSkullTech; switch(mRenderOptions) { case RenderOptions::Lighting: activeTech = Effects::BasicFX->Light3Tech; activeSkullTech = Effects::BasicFX->Light3Tech; break; case RenderOptions::Textures: activeTech = Effects::BasicFX->Light3TexTech; activeSkullTech = Effects::BasicFX->Light3Tech; break; case RenderOptions::TexturesAndFog: activeTech = Effects::BasicFX->Light3TexFogTech; activeSkullTech = Effects::BasicFX->Light3FogTech; break; } D3DX11_TECHNIQUE_DESC techDesc; // // Draw the floor and walls to the back buffer as normal. // activeTech->GetDesc( &techDesc ); for(UINT p = 0; p < techDesc.Passes; ++p) { ID3DX11EffectPass* pass = activeTech->GetPassByIndex( p ); md3dImmediateContext->IASetVertexBuffers(0, 1, &mRoomVB, &stride, &offset); // Set per object constants. XMMATRIX world = XMLoadFloat4x4(&mRoomWorld); XMMATRIX worldInvTranspose = MathHelper::InverseTranspose(world); XMMATRIX worldViewProj = world*view*proj; Effects::BasicFX->SetWorld(world); Effects::BasicFX->SetWorldInvTranspose(worldInvTranspose); Effects::BasicFX->SetWorldViewProj(worldViewProj); Effects::BasicFX->SetTexTransform(XMMatrixIdentity()); Effects::BasicFX->SetMaterial(mRoomMat); // Floor Effects::BasicFX->SetDiffuseMap(mFloorDiffuseMapSRV); pass->Apply(0, md3dImmediateContext); md3dImmediateContext->Draw(6, 0); // Wall Effects::BasicFX->SetDiffuseMap(mWallDiffuseMapSRV); pass->Apply(0, md3dImmediateContext); md3dImmediateContext->Draw(18, 6); } // // Draw the skull to the back buffer as normal. // activeSkullTech->GetDesc( &techDesc ); for(UINT p = 0; p < techDesc.Passes; ++p) { ID3DX11EffectPass* pass = activeSkullTech->GetPassByIndex( p ); md3dImmediateContext->IASetVertexBuffers(0, 1, &mSkullVB, &stride, &offset); md3dImmediateContext->IASetIndexBuffer(mSkullIB, DXGI_FORMAT_R32_UINT, 0); XMMATRIX world = XMLoadFloat4x4(&mSkullWorld); XMMATRIX worldInvTranspose = MathHelper::InverseTranspose(world); XMMATRIX worldViewProj = world*view*proj; Effects::BasicFX->SetWorld(world); Effects::BasicFX->SetWorldInvTranspose(worldInvTranspose); Effects::BasicFX->SetWorldViewProj(worldViewProj); Effects::BasicFX->SetMaterial(mSkullMat); pass->Apply(0, md3dImmediateContext); md3dImmediateContext->DrawIndexed(mSkullIndexCount, 0, 0); } // // Draw the mirror to stencil buffer only. // activeTech->GetDesc( &techDesc ); for(UINT p = 0; p < techDesc.Passes; ++p) { ID3DX11EffectPass* pass = activeTech->GetPassByIndex( p ); md3dImmediateContext->IASetVertexBuffers(0, 1, &mRoomVB, &stride, &offset); // Set per object constants. XMMATRIX world = XMLoadFloat4x4(&mRoomWorld); XMMATRIX worldInvTranspose = MathHelper::InverseTranspose(world); XMMATRIX worldViewProj = world*view*proj; Effects::BasicFX->SetWorld(world); Effects::BasicFX->SetWorldInvTranspose(worldInvTranspose); Effects::BasicFX->SetWorldViewProj(worldViewProj); Effects::BasicFX->SetTexTransform(XMMatrixIdentity()); // Do not write to render target. md3dImmediateContext->OMSetBlendState(RenderStates::NoRenderTargetWritesBS, blendFactor, 0xffffffff); // Render visible mirror pixels to stencil buffer. // Do not write mirror depth to depth buffer at this point, otherwise it will occlude the reflection. md3dImmediateContext->OMSetDepthStencilState(RenderStates::MarkMirrorDSS, 1); pass->Apply(0, md3dImmediateContext); md3dImmediateContext->Draw(6, 24); // Restore states. md3dImmediateContext->OMSetDepthStencilState(0, 0); md3dImmediateContext->OMSetBlendState(0, blendFactor, 0xffffffff); } // // Draw the skull reflection. // activeSkullTech->GetDesc( &techDesc ); for(UINT p = 0; p < techDesc.Passes; ++p) { ID3DX11EffectPass* pass = activeSkullTech->GetPassByIndex( p ); md3dImmediateContext->IASetVertexBuffers(0, 1, &mSkullVB, &stride, &offset); md3dImmediateContext->IASetIndexBuffer(mSkullIB, DXGI_FORMAT_R32_UINT, 0); XMVECTOR mirrorPlane = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f); // xy plane XMMATRIX R = XMMatrixReflect(mirrorPlane); XMMATRIX world = XMLoadFloat4x4(&mSkullWorld) * R; XMMATRIX worldInvTranspose = MathHelper::InverseTranspose(world); XMMATRIX worldViewProj = world*view*proj; Effects::BasicFX->SetWorld(world); Effects::BasicFX->SetWorldInvTranspose(worldInvTranspose); Effects::BasicFX->SetWorldViewProj(worldViewProj); Effects::BasicFX->SetMaterial(mSkullMat); // Cache the old light directions, and reflect the light directions. XMFLOAT3 oldLightDirections[3]; for(int i = 0; i < 3; ++i) { oldLightDirections[i] = mDirLights[i].Direction; XMVECTOR lightDir = XMLoadFloat3(&mDirLights[i].Direction); XMVECTOR reflectedLightDir = XMVector3TransformNormal(lightDir, R); XMStoreFloat3(&mDirLights[i].Direction, reflectedLightDir); } Effects::BasicFX->SetDirLights(mDirLights); // Cull clockwise triangles for reflection. md3dImmediateContext->RSSetState(RenderStates::CullClockwiseRS); // Only draw reflection into visible mirror pixels as marked by the stencil buffer. md3dImmediateContext->OMSetDepthStencilState(RenderStates::DrawReflectionDSS, 1); pass->Apply(0, md3dImmediateContext); md3dImmediateContext->DrawIndexed(mSkullIndexCount, 0, 0); // Restore default states. md3dImmediateContext->RSSetState(0); md3dImmediateContext->OMSetDepthStencilState(0, 0); // Restore light directions. for(int i = 0; i < 3; ++i) { mDirLights[i].Direction = oldLightDirections[i]; } Effects::BasicFX->SetDirLights(mDirLights); } // // Draw the mirror to the back buffer as usual but with transparency // blending so the reflection shows through. // activeTech->GetDesc( &techDesc ); for(UINT p = 0; p < techDesc.Passes; ++p) { ID3DX11EffectPass* pass = activeTech->GetPassByIndex( p ); md3dImmediateContext->IASetVertexBuffers(0, 1, &mRoomVB, &stride, &offset); // Set per object constants. XMMATRIX world = XMLoadFloat4x4(&mRoomWorld); XMMATRIX worldInvTranspose = MathHelper::InverseTranspose(world); XMMATRIX worldViewProj = world*view*proj; Effects::BasicFX->SetWorld(world); Effects::BasicFX->SetWorldInvTranspose(worldInvTranspose); Effects::BasicFX->SetWorldViewProj(worldViewProj); Effects::BasicFX->SetTexTransform(XMMatrixIdentity()); Effects::BasicFX->SetMaterial(mMirrorMat); Effects::BasicFX->SetDiffuseMap(mMirrorDiffuseMapSRV); // Mirror md3dImmediateContext->OMSetBlendState(RenderStates::TransparentBS, blendFactor, 0xffffffff); pass->Apply(0, md3dImmediateContext); md3dImmediateContext->Draw(6, 24); } // // Draw the skull shadow. // activeSkullTech->GetDesc( &techDesc ); for(UINT p = 0; p < techDesc.Passes; ++p) { ID3DX11EffectPass* pass = activeSkullTech->GetPassByIndex( p ); md3dImmediateContext->IASetVertexBuffers(0, 1, &mSkullVB, &stride, &offset); md3dImmediateContext->IASetIndexBuffer(mSkullIB, DXGI_FORMAT_R32_UINT, 0); XMVECTOR shadowPlane = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); // xz plane XMVECTOR toMainLight = -XMLoadFloat3(&mDirLights[0].Direction); XMMATRIX S = XMMatrixShadow(shadowPlane, toMainLight); XMMATRIX shadowOffsetY = XMMatrixTranslation(0.0f, 0.001f, 0.0f); // Set per object constants. XMMATRIX world = XMLoadFloat4x4(&mSkullWorld)*S*shadowOffsetY; XMMATRIX worldInvTranspose = MathHelper::InverseTranspose(world); XMMATRIX worldViewProj = world*view*proj; Effects::BasicFX->SetWorld(world); Effects::BasicFX->SetWorldInvTranspose(worldInvTranspose); Effects::BasicFX->SetWorldViewProj(worldViewProj); Effects::BasicFX->SetMaterial(mShadowMat); md3dImmediateContext->OMSetDepthStencilState(RenderStates::NoDoubleBlendDSS, 0); pass->Apply(0, md3dImmediateContext); md3dImmediateContext->DrawIndexed(mSkullIndexCount, 0, 0); // Restore default states. md3dImmediateContext->OMSetBlendState(0, blendFactor, 0xffffffff); md3dImmediateContext->OMSetDepthStencilState(0, 0); } HR(mSwapChain->Present(0, 0)); }
void Mesh::Update() { //WORLD MATRIX m_world = XMMatrixIdentity(); }
//---------------------------------------------------------------------------- void CTimeLine::Draw() { if(!IsEnabled()) return; unsigned int PrevFrame = 1 - m_CurrFrame; // draw the previously recorded frame, since the current one is still being filled unsigned long long FrameDuration = m_FrameEnd[PrevFrame] - m_FrameStart[PrevFrame]; unsigned long long ClockFrequency = CTime::GetClockFrequency(); unsigned long DurationMicroSecs = (unsigned long)(FrameDuration * 1000000 / ClockFrequency); unsigned int Width, Height; m_rRenderer->GetViewportSize(Width, Height); // Draw the total frame duration char FrameDurationSt[256]; sprintf_s(FrameDurationSt, 255, "Frame %d.%dms", DurationMicroSecs / 1000, DurationMicroSecs % 1000); CColor White(255, 255, 255, 255); m_rDebugGUI->DrawString((float)scLeftMargin, (float)scTopMargin, FrameDurationSt, White); if(m_pMaterial == NULL) { CMaterialPlainColor::CParameters Params("CTimeline.PlainColorParams", CMaterialPlainColor::eViewSpace); m_pMaterial = &m_rMaterialSystem->GetMaterial<CMaterialPlainColor>(&Params); } unsigned int BarStart = scLeftMargin + scThreadName * 8 + 5; // 8 is the debug fonts character width unsigned int BarEnd = Width - scRightMargin; float PixelWidth = 2.0f / (float)Width; float PixelHeight = 2.0f / (float)Height; float ViewSpaceFrameWidth = (BarEnd - BarStart) * PixelWidth; float MicroSecondsToViewSpace = ViewSpaceFrameWidth / DurationMicroSecs; XMMATRIX LocalToWorld = XMMatrixIdentity(); XMFLOAT2 Uv0(0.0f, 0.0f); m_rUtilityDraw->BeginTriangleList(); float X0; float X1; float Y0 = 1.0f - (scTopMargin + scBarHeight) * PixelHeight; // After frame duration float Y1 = Y0 - scBarHeight * PixelHeight; for(unsigned int ThreadIndex = 0; ThreadIndex < scMaxThreads; ThreadIndex++) { X0 = -1.0f + BarStart * PixelWidth; X1 = X0; const CEventDesc* pEventDesc = m_pEventDescs[ThreadIndex]; if(pEventDesc) { if ((m_EventRead[ThreadIndex] == m_EventEnd[ThreadIndex]) && m_pActive[ThreadIndex]) { CEvent* pEvent = m_pActive[ThreadIndex]; if (pEvent->m_State == CEvent::eStarted) { DrawEvent( pEvent, PrevFrame, ClockFrequency, ThreadIndex, MicroSecondsToViewSpace, X0, X1, Y0, Y1, PixelWidth, PixelHeight, pEventDesc); } } for ( ;(m_EventRead[ThreadIndex] != m_EventEnd[ThreadIndex]); m_EventRead[ThreadIndex] = (m_EventRead[ThreadIndex] + 1) % scMaxEvents) { unsigned int EventIndex = m_EventRead[ThreadIndex]; CEvent* pEvent = &m_Events[ThreadIndex][EventIndex]; DrawEvent(pEvent, PrevFrame, ClockFrequency, ThreadIndex, MicroSecondsToViewSpace, X0, X1, Y0, Y1, PixelWidth, PixelHeight, pEventDesc); } } Y0 = Y1; Y1 = Y0 - scBarHeight * PixelHeight; } m_rUtilityDraw->EndTriangleList(LocalToWorld, m_pMaterial, CRenderer::eDepthNone, CRenderer::eBlendModulate); // Draw thread names Y0 = scTopMargin + scBarHeight; // After frame duration, this is in pixels not view space X0 = scLeftMargin; for(unsigned int ThreadIndex = 0; ThreadIndex < scMaxThreads; ThreadIndex++) { if(m_pThreadNames[ThreadIndex]) { m_rDebugGUI->DrawString(X0, Y0, m_pThreadNames[ThreadIndex], White); Y0 += scBarHeight; } } // Now draw all events for the current thread const CEventDesc* pEventDesc = m_pEventDescs[m_CurrentThread]; if(pEventDesc) { while(pEventDesc->m_pName) { sprintf_s(FrameDurationSt, 255, "%-10s %d.%dms", pEventDesc->m_pName, m_Duration[pEventDesc->m_Type] / 1000, m_Duration[pEventDesc->m_Type] % 1000); m_rDebugGUI->DrawString(X0, Y0, FrameDurationSt, pEventDesc->m_Color); Y0 += scBarHeight; m_Duration[pEventDesc->m_Type] = 0; pEventDesc++; } } }