void CrateApp::BuildGeometryBuffers() { GeometryGenerator::MeshData box; GeometryGenerator geoGen; geoGen.CreateBox(1.0f, 1.0f, 1.0f, box); // Cache the vertex offsets to each object in the concatenated vertex buffer. mBoxVertexOffset = 0; // Cache the index count of each object. mBoxIndexCount = box.Indices.size(); // Cache the starting index for each object in the concatenated index buffer. mBoxIndexOffset = 0; UINT totalVertexCount = box.Vertices.size(); UINT totalIndexCount = mBoxIndexCount; // // Extract the vertex elements we are interested in and pack the // vertices of all the meshes into one vertex buffer. // std::vector<Vertex::Basic32> vertices(totalVertexCount); UINT k = 0; for(size_t i = 0; i < box.Vertices.size(); ++i, ++k) { vertices[k].Pos = box.Vertices[i].Position; vertices[k].Normal = box.Vertices[i].Normal; vertices[k].Tex = box.Vertices[i].TexC; } D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex::Basic32) * totalVertexCount; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vertices[0]; HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mBoxVB)); // // Pack the indices of all the meshes into one index buffer. // std::vector<UINT> indices; indices.insert(indices.end(), box.Indices.begin(), box.Indices.end()); D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT) * totalIndexCount; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &indices[0]; HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mBoxIB)); }
void wam::BuildGeometryBuffers() { GeometryGenerator geoGen; geoGen.CreateGrid(20.0f, 30.0f, 60, 40, grid); geoGen.CreateSphere(0.5f, 20, 20, sphere); //geoGen.CreateGeosphere(0.5f, 2, sphere); geoGen.CreateCylinder(0.5f, 0.3f, 3.0f, 20, 20, cylinder); // Cache the vertex offsets to each object in the concatenated vertex buffer. mGridVertexOffset = 0; mSphereVertexOffset = mGridVertexOffset + grid.Vertices.size(); mCylinderVertexOffset = mSphereVertexOffset + sphere.Vertices.size(); // Cache the index count of each object. mGridIndexCount = grid.Indices.size(); mSphereIndexCount = sphere.Indices.size(); mCylinderIndexCount = cylinder.Indices.size(); // Cache the starting index for each object in the concatenated index buffer. mGridIndexOffset = 0; mSphereIndexOffset = mGridIndexOffset + mGridIndexCount; mCylinderIndexOffset = mSphereIndexOffset + mSphereIndexCount; UINT totalVertexCount = grid.Vertices.size() + sphere.Vertices.size() + cylinder.Vertices.size(); UINT totalIndexCount = mGridIndexCount + mSphereIndexCount + mCylinderIndexCount; // // Extract the vertex elements we are interested in and pack the // vertices of all the meshes into one vertex buffer. // std::vector<Vertex> vertices(totalVertexCount); XMFLOAT4 black(0.0f, 0.0f, 0.0f, 1.0f); UINT k = 0; for(size_t i = 0; i < grid.Vertices.size(); ++i, ++k) { vertices[k].Pos = grid.Vertices[i].Position; vertices[k].Color = black; } for(size_t i = 0; i < sphere.Vertices.size(); ++i, ++k) { vertices[k].Pos = sphere.Vertices[i].Position; vertices[k].Color = black; } for(size_t i = 0; i < cylinder.Vertices.size(); ++i, ++k) { vertices[k].Pos = cylinder.Vertices[i].Position; vertices[k].Color = black; } D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex) * totalVertexCount; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vertices[0]; HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mVB)); // // Pack the indices of all the meshes into one index buffer. // std::vector<UINT> indices; indices.insert(indices.end(), grid.Indices.begin(), grid.Indices.end()); indices.insert(indices.end(), sphere.Indices.begin(), sphere.Indices.end()); indices.insert(indices.end(), cylinder.Indices.begin(), cylinder.Indices.end()); D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT) * totalIndexCount; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &indices[0]; HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mIB)); }
WaterDemo::WaterDemo(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP) : D3DApp(hInstance, winCaption, devType, requestedVP) { if(!checkDeviceCaps()) { MessageBox(0, "checkDeviceCaps() Failed", 0, 0); PostQuitMessage(0); } InitAllVertexDeclarations(); mLight.dirW = D3DXVECTOR3(0.0f, -2.0f, -1.0f); D3DXVec3Normalize(&mLight.dirW, &mLight.dirW); mLight.ambient = D3DXCOLOR(0.3f, 0.3f, 0.3f, 1.0f); mLight.diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); mLight.spec = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f); mGfxStats = new GfxStats(); mSky = new Sky("grassenvmap1024.dds", 10000.0f); D3DXMATRIX waterWorld; D3DXMatrixTranslation(&waterWorld, 0.0f, 2.0f, 0.0f); Mtrl waterMtrl; waterMtrl.ambient = D3DXCOLOR(0.26f, 0.23f, 0.3f, 0.90f); waterMtrl.diffuse = D3DXCOLOR(0.26f, 0.23f, 0.3f, 0.90f); waterMtrl.spec = 1.0f*WHITE; waterMtrl.specPower = 64.0f; Water::InitInfo waterInitInfo; waterInitInfo.dirLight = mLight; waterInitInfo.mtrl = waterMtrl; waterInitInfo.vertRows = 128; waterInitInfo.vertCols = 128; waterInitInfo.dx = 1.0f; waterInitInfo.dz = 1.0f; waterInitInfo.waveMapFilename0 = "wave0.dds"; waterInitInfo.waveMapFilename1 = "wave1.dds"; waterInitInfo.waveMapVelocity0 = D3DXVECTOR2(0.05f, 0.08f); waterInitInfo.waveMapVelocity1 = D3DXVECTOR2(-0.02f, 0.1f); waterInitInfo.texScale = 16.0f; waterInitInfo.toWorld = waterWorld; mWater = new Water(waterInitInfo); mWater->setEnvMap(mSky->getEnvMap()); ID3DXMesh* tempMesh = 0; LoadXFile("BasicColumnScene.x", &tempMesh, mSceneMtrls, mSceneTextures); // Get the vertex declaration for the NMapVertex. D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE]; UINT numElems = 0; HR(NMapVertex::Decl->GetDeclaration(elems, &numElems)); // Clone the mesh to the NMapVertex format. ID3DXMesh* clonedTempMesh = 0; HR(tempMesh->CloneMesh(D3DXMESH_MANAGED, elems, gd3dDevice, &clonedTempMesh)); // Now use D3DXComputeTangentFrameEx to build the TNB-basis for each vertex // in the mesh. HR(D3DXComputeTangentFrameEx( clonedTempMesh, // Input mesh D3DDECLUSAGE_TEXCOORD, 0, // Vertex element of input tex-coords. D3DDECLUSAGE_BINORMAL, 0, // Vertex element to output binormal. D3DDECLUSAGE_TANGENT, 0, // Vertex element to output tangent. D3DDECLUSAGE_NORMAL, 0, // Vertex element to output normal. 0, // Options 0, // Adjacency 0.01f, 0.25f, 0.01f, // Thresholds for handling errors &mSceneMesh, // Output mesh 0)); // Vertex Remapping // Done with temps. ReleaseCOM(tempMesh); ReleaseCOM(clonedTempMesh); D3DXMatrixIdentity(&mSceneWorld); D3DXMatrixIdentity(&mSceneWorldInv); HR(D3DXCreateTextureFromFile(gd3dDevice, "floor_nmap.bmp", &mSceneNormalMaps[0])); HR(D3DXCreateTextureFromFile(gd3dDevice, "bricks_nmap.bmp", &mSceneNormalMaps[1])); HR(D3DXCreateTextureFromFile(gd3dDevice, "whitetex.dds", &mWhiteTex)); // Initialize camera. gCamera->pos().y = 7.0f; gCamera->pos().z = -30.0f; gCamera->setSpeed(10.0f); mGfxStats->addVertices(mSceneMesh->GetNumVertices()); mGfxStats->addTriangles(mSceneMesh->GetNumFaces()); mGfxStats->addVertices(mWater->getNumVertices()); mGfxStats->addTriangles(mWater->getNumTriangles()); mGfxStats->addVertices(mSky->getNumVertices()); mGfxStats->addTriangles(mSky->getNumTriangles()); buildFX(); onResetDevice(); }
void Terrain::onLostDevice() { HR(mFX->OnLostDevice()); }
void LightDemo::DrawScene() { m_dxImmediateContext->ClearRenderTargetView(m_renderTargetView.Get(), reinterpret_cast<const float*>(&oc::Colors::LightSteelBlue)); m_dxImmediateContext->ClearDepthStencilView(m_depthStencilView.Get(), D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0); m_dxImmediateContext->IASetInputLayout(m_inputLayout.Get()); m_dxImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); uint32 stride = sizeof(Vertex); uint32 offset = 0; // Set constants XMMATRIX view = XMLoadFloat4x4(&m_view); XMMATRIX proj = XMLoadFloat4x4(&m_proj); XMMATRIX viewProj = view*proj; // Set per frame constants. m_fxDirLight->SetRawValue(&m_dirLight, 0, sizeof(m_dirLight)); m_fxPointLight->SetRawValue(&m_pointLight, 0, sizeof(m_pointLight)); m_fxSpotLight->SetRawValue(&m_spotLight, 0, sizeof(m_spotLight)); m_fxEyePosW->SetRawValue(&m_camPosition, 0, sizeof(m_camPosition)); D3DX11_TECHNIQUE_DESC techDesc; m_tech->GetDesc(&techDesc); for(uint32 p = 0; p < techDesc.Passes; ++p) { //Draw the land m_dxImmediateContext->IASetVertexBuffers(0, 1, m_landVB.GetAddressOf(), &stride, &offset); m_dxImmediateContext->IASetIndexBuffer(m_landIB.Get(), DXGI_FORMAT_R32_UINT, 0); //Set per object constants XMMATRIX world = XMLoadFloat4x4(&m_landWorld); XMMATRIX worldInvTranspose = MathHelper::InverseTranspose(world); XMMATRIX worldViewProj = world*viewProj; m_fxWorld->SetMatrix(reinterpret_cast<float*>(&world)); m_fxWorldInvTranspose->SetMatrix(reinterpret_cast<float*>(&worldInvTranspose)); m_fxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj)); m_fxMaterial->SetRawValue(&m_landMat, 0, sizeof(m_landMat)); m_tech->GetPassByIndex(p)->Apply(0, m_dxImmediateContext.Get()); m_dxImmediateContext->DrawIndexed(m_landIndexCount, 0, 0); //Draw the wave m_dxImmediateContext->IASetVertexBuffers(0, 1, m_wavesVB.GetAddressOf(), &stride, &offset); m_dxImmediateContext->IASetIndexBuffer(m_wavesIB.Get(), DXGI_FORMAT_R32_UINT, 0); world = XMLoadFloat4x4(&m_wavesWorld); worldInvTranspose = MathHelper::InverseTranspose(world); worldViewProj = world*viewProj; m_fxWorld->SetMatrix(reinterpret_cast<float*>(&world)); m_fxWorldInvTranspose->SetMatrix(reinterpret_cast<float*>(&worldInvTranspose)); m_fxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj)); m_fxMaterial->SetRawValue(&m_wavesMat, 0, sizeof(m_wavesMat)); m_tech->GetPassByIndex(p)->Apply(0, m_dxImmediateContext.Get()); m_dxImmediateContext->DrawIndexed(3*m_waves.TriangleCount(), 0, 0); } HR(m_swapChain->Present(0, 0)); }
void Shape::BuildGeometryBuffers() { GeometryGenerator::MeshData grid; GeometryGenerator::MeshData box; GeometryGenerator::MeshData sphere; GeometryGenerator::MeshData cylinder; GeometryGenerator geoGen; geoGen.CreateGrid(20.0f, 30.0f, 60, 40, grid); geoGen.CreateBox(1.0f, 1.0f, 1.0f, box); geoGen.CreateGeosphere(0.5f, 3, sphere); //geoGen.CreateSphere(1.0f, 30, 30, sphere); geoGen.CreateCylinder(0.5f, 0.3f, 3.0f, 30, 30, cylinder); mGridVertexOffset = 0; mBoxVertexOffset = grid.Vertices.size(); mSphereVertexOffset = mBoxVertexOffset + box.Vertices.size(); mCylinderVertexOffset = mSphereVertexOffset + sphere.Vertices.size(); mGridIndexCount = grid.Indices.size(); mBoxIndexCount = box.Indices.size(); mSphereIndexCount = sphere.Indices.size(); mCylinderIndexCount = cylinder.Indices.size(); mGridIndexOffset = 0; mBoxIndexOffset = mGridIndexCount; mSphereIndexOffset = mBoxIndexOffset + mBoxIndexCount; mCylinderIndexOffset = mSphereIndexOffset + mSphereIndexCount; UINT totalVertexCount = box.Vertices.size() + grid.Vertices.size() + sphere.Vertices.size() + cylinder.Vertices.size(); UINT totalIndexCount = mBoxIndexCount + mGridIndexCount + mSphereIndexCount + mCylinderIndexCount; #pragma region Create Vertices Buffer std::vector<Vertex> vertices(totalVertexCount); XMFLOAT4 color = *(XMFLOAT4*)&Colors::Red; UINT k = 0; for ( size_t i = 0; i < grid.Vertices.size(); ++i, ++k ) { vertices[k].Pos = grid.Vertices[i].Position; vertices[k].Color = *(XMFLOAT4*)&Colors::Blue; } for ( size_t i = 0; i < box.Vertices.size(); ++i, ++k ) { vertices[k].Pos = box.Vertices[i].Position; vertices[k].Color = *(XMFLOAT4*)&Colors::Magenta; } for ( size_t i = 0; i < sphere.Vertices.size(); ++i, ++k ) { vertices[k].Pos = sphere.Vertices[i].Position; vertices[k].Color = *(XMFLOAT4*)&Colors::Yellow; } for ( size_t i = 0; i < cylinder.Vertices.size(); ++i, ++k ) { vertices[k].Pos = cylinder.Vertices[i].Position; vertices[k].Color = *(XMFLOAT4*)&Colors::Red; } D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex)*totalVertexCount; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; vbd.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vertices[0]; HR(mD3DDevice->CreateBuffer(&vbd, &vinitData, &mShapeVB)); #pragma endregion #pragma region Create Indices Buffer std::vector<UINT> indices; indices.clear(); indices.insert(indices.end(), grid.Indices.begin(), grid.Indices.end()); indices.insert(indices.end(), box.Indices.begin(), box.Indices.end()); indices.insert(indices.end(), sphere.Indices.begin(), sphere.Indices.end()); indices.insert(indices.end(), cylinder.Indices.begin(), cylinder.Indices.end()); D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT)*totalIndexCount; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; ibd.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &indices[0]; HR(mD3DDevice->CreateBuffer(&ibd, &iinitData, &mShapeIB)); #pragma endregion }
void Terrain::buildGeometry() { //=============================================================== // Create one large mesh for the grid in system memory. DWORD numTris = (mVertRows-1)*(mVertCols-1)*2; DWORD numVerts = mVertRows*mVertCols; ID3DXMesh* mesh = 0; D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE]; UINT numElems = 0; HR(VertexPNT::Decl->GetDeclaration(elems, &numElems)); HR(D3DXCreateMesh(numTris, numVerts, D3DXMESH_SYSTEMMEM|D3DXMESH_32BIT, elems, gd3dDevice, &mesh)); //=============================================================== // Write the grid vertices and triangles to the mesh. VertexPNT* v = 0; HR(mesh->LockVertexBuffer(0, (void**)&v)); std::vector<D3DXVECTOR3> verts; std::vector<DWORD> indices; GenTriGrid(mVertRows, mVertCols, mDX, mDZ, D3DXVECTOR3(0.0f, 0.0f, 0.0f), verts, indices); float w = mWidth; float d = mDepth; for(UINT i = 0; i < mesh->GetNumVertices(); ++i) { // We store the grid vertices in a linear array, but we can // convert the linear array index to an (r, c) matrix index. int r = i / mVertCols; int c = i % mVertCols; v[i].pos = verts[i]; v[i].pos.y = mHeightmap(r, c); v[i].tex0.x = (v[i].pos.x + (0.5f*w)) / w; v[i].tex0.y = (v[i].pos.z - (0.5f*d)) / -d; } // Write triangle data so we can compute normals. DWORD* indexBuffPtr = 0; HR(mesh->LockIndexBuffer(0, (void**)&indexBuffPtr)); for(UINT i = 0; i < mesh->GetNumFaces(); ++i) { indexBuffPtr[i*3+0] = indices[i*3+0]; indexBuffPtr[i*3+1] = indices[i*3+1]; indexBuffPtr[i*3+2] = indices[i*3+2]; } HR(mesh->UnlockIndexBuffer()); // Compute Vertex Normals. HR(D3DXComputeNormals(mesh, 0)); //=============================================================== // Now break the grid up into subgrid meshes. // Find out the number of subgrids we'll have. For example, if // m = 513, n = 257, SUBGRID_VERT_ROWS = SUBGRID_VERT_COLS = 33, // then subGridRows = 512/32 = 16 and sibGridCols = 256/32 = 8. int subGridRows = (mVertRows-1) / (SubGrid::NUM_ROWS-1); int subGridCols = (mVertCols-1) / (SubGrid::NUM_COLS-1); for(int r = 0; r < subGridRows; ++r) { for(int c = 0; c < subGridCols; ++c) { // Rectangle that indicates (via matrix indices ij) the // portion of grid vertices to use for this subgrid. RECT R = { c * (SubGrid::NUM_COLS-1), r * (SubGrid::NUM_ROWS-1), (c+1) * (SubGrid::NUM_COLS-1), (r+1) * (SubGrid::NUM_ROWS-1) }; buildSubGridMesh(R, v); } } HR(mesh->UnlockVertexBuffer()); ReleaseCOM(mesh); // Done with global mesh. }
//----------------------------------------------------------------------------- // Name:DInputClass::Init() // Desc: 初始化DirectInput键盘及鼠标输入设备 //----------------------------------------------------------------------------- HRESULT DInputClass::Init( HWND hWnd,HINSTANCE hInstance,DWORD keyboardCoopFlags, DWORD mouseCoopFlags ) { HRESULT hr; //初始化一个IDirectInput8接口对象 HR(DirectInput8Create( hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8,(void**)&m_pDirectInput,NULL )); //进行键盘设备的初始化 HR( m_pDirectInput->CreateDevice( GUID_SysKeyboard, &m_KeyboardDevice, NULL )); HR( m_KeyboardDevice->SetCooperativeLevel( hWnd, keyboardCoopFlags)); HR( m_KeyboardDevice->SetDataFormat( &c_dfDIKeyboard )); HR( m_KeyboardDevice->Acquire( )); HR( m_KeyboardDevice->Poll( )); //进行鼠标设备的初始化 HR( m_pDirectInput->CreateDevice( GUID_SysMouse, &m_MouseDevice, NULL )); HR( m_MouseDevice->SetCooperativeLevel( hWnd,mouseCoopFlags)); HR( m_MouseDevice->SetDataFormat( &c_dfDIMouse )); HR( m_MouseDevice->Acquire( )); HR( m_KeyboardDevice->Poll( )); return S_OK; }
void StencilMirrorDemo::onLostDevice() { mGfxStats->onLostDevice(); HR(mFX->OnLostDevice()); }
void SkinnedMesh::buildSkinnedMesh(ID3DXMesh* mesh) { //==================================================================== // First add a normal component and 2D texture coordinates component. D3DVERTEXELEMENT9 elements[64]; UINT numElements = 0; VertexPNT::Decl->GetDeclaration(elements, &numElements); ID3DXMesh* tempMesh = 0; HR(mesh->CloneMesh(D3DXMESH_SYSTEMMEM, elements, gd3dDevice, &tempMesh)); if( !hasNormals(tempMesh) ) HR(D3DXComputeNormals(tempMesh, 0)); //==================================================================== // Optimize the mesh; in particular, the vertex cache. DWORD* adj = new DWORD[tempMesh->GetNumFaces()*3]; ID3DXBuffer* remap = 0; HR(tempMesh->GenerateAdjacency(EPSILON, adj)); ID3DXMesh* optimizedTempMesh = 0; HR(tempMesh->Optimize(D3DXMESH_SYSTEMMEM | D3DXMESHOPT_VERTEXCACHE | D3DXMESHOPT_ATTRSORT, adj, 0, 0, &remap, &optimizedTempMesh)); ReleaseCOM(tempMesh); // Done w/ this mesh. delete[] adj; // Done with buffer. // In the .X file (specifically the array DWORD vertexIndices[nWeights] // data member of the SkinWeights template) each bone has an array of // indices which identify the vertices of the mesh that the bone influences. // Because we have just rearranged the vertices (from optimizing), the vertex // indices of a bone are obviously incorrect (i.e., they index to vertices the bone // does not influence since we moved vertices around). In order to update a bone's // vertex indices to the vertices the bone _does_ influence, we simply need to specify // where we remapped the vertices to, so that the vertex indices can be updated to // match. This is done with the ID3DXSkinInfo::Remap method. HR(mSkinInfo->Remap(optimizedTempMesh->GetNumVertices(), (DWORD*)remap->GetBufferPointer())); ReleaseCOM(remap); // Done with remap info. //==================================================================== // The vertex format of the source mesh does not include vertex weights // nor bone index data, which are both needed for vertex blending. // Therefore, we must convert the source mesh to an "indexed-blended-mesh," // which does have the necessary data. DWORD numBoneComboEntries = 0; ID3DXBuffer* boneComboTable = 0; HR(mSkinInfo->ConvertToIndexedBlendedMesh(optimizedTempMesh, D3DXMESH_MANAGED | D3DXMESH_WRITEONLY, MAX_NUM_BONES_SUPPORTED, 0, 0, 0, 0, &mMaxVertInfluences, &numBoneComboEntries, &boneComboTable, &mSkinnedMesh)); ReleaseCOM(optimizedTempMesh); // Done with tempMesh. ReleaseCOM(boneComboTable); // Don't need bone table. #if defined(DEBUG) | defined(_DEBUG) // Output to the debug output the vertex declaration of the mesh at this point. // This is for insight only to see what exactly ConvertToIndexedBlendedMesh // does to the vertex declaration. D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE]; HR(mSkinnedMesh->GetDeclaration(elems)); OutputDebugString("\nVertex Format After ConvertToIndexedBlendedMesh\n"); int i = 0; while( elems[i].Stream != 0xff ) // While not D3DDECL_END() { if( elems[i].Type == D3DDECLTYPE_FLOAT1) OutputDebugString("Type = D3DDECLTYPE_FLOAT1; "); if( elems[i].Type == D3DDECLTYPE_FLOAT2) OutputDebugString("Type = D3DDECLTYPE_FLOAT2; "); if( elems[i].Type == D3DDECLTYPE_FLOAT3) OutputDebugString("Type = D3DDECLTYPE_FLOAT3; "); if( elems[i].Type == D3DDECLTYPE_UBYTE4) OutputDebugString("Type = D3DDECLTYPE_UBYTE4; "); if( elems[i].Usage == D3DDECLUSAGE_POSITION) OutputDebugString("Usage = D3DDECLUSAGE_POSITION\n"); if( elems[i].Usage == D3DDECLUSAGE_BLENDWEIGHT) OutputDebugString("Usage = D3DDECLUSAGE_BLENDWEIGHT\n"); if( elems[i].Usage == D3DDECLUSAGE_BLENDINDICES) OutputDebugString("Usage = D3DDECLUSAGE_BLENDINDICES\n"); if( elems[i].Usage == D3DDECLUSAGE_NORMAL) OutputDebugString("Usage = D3DDECLUSAGE_NORMAL\n"); if( elems[i].Usage == D3DDECLUSAGE_TEXCOORD) OutputDebugString("Usage = D3DDECLUSAGE_TEXCOORD\n"); ++i; } #endif }
void SkinnedMesh::draw() { HR(mSkinnedMesh->DrawSubset(0)); }
void GfxStats::onResetDevice() { HR(mFont->OnResetDevice()); }
void GfxStats::onLostDevice() { HR(mFont->OnLostDevice()); }
bool D3DApp::InitDirect3D() { // Create the device and device context. UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; HRESULT hr = D3D11CreateDevice( 0, // default adapter D3D_DRIVER_TYPE_HARDWARE,// D3D_DRIVER_TYPE_HARDWARE - 3D hardware acceleration for rendering 0, // no software driver createDeviceFlags, 0, 0, // default feature level array D3D11_SDK_VERSION, // This never changes &md3dDevice, // The now created device &featureLevel, // Greatest feature level supported &md3dImmediateContext); // The now created device context if( FAILED(hr) ) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } // This is the order that the feature levels are tried if( featureLevel == D3D_FEATURE_LEVEL_11_0 ) { printf("Using Direct3D Feature Level 11.0\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_10_1 ) { printf("Using Direct3D Feature Level 10.1\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_10_0 ) { printf("Using Direct3D Feature Level 10.0\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_9_3 ) { printf("Using Direct3D Feature Level 9.3\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_9_2 ) { printf("Using Direct3D Feature Level 9.2\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_9_1 ) { printf("Using Direct3D Feature Level 9.1\n"); } // Check 4X MSAA quality support for our back buffer format. // All Direct3D 11 capable devices support 4X MSAA for all render // target formats, so we only need to check quality support. HR(md3dDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality)); // If m4xMsaaQuality > 0 4x MSAA is supported //assert( m4xMsaaQuality > 0 ); // Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain. DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = mClientWidth; sd.BufferDesc.Height = mClientHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Use 4X MSAA? if( mEnable4xMsaa ) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m4xMsaaQuality-1; } // No MSAA else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Rendering to the back buffer sd.BufferCount = 1; // Number of back buffers sd.OutputWindow = mhMainWnd; // Handle to the window we are rendering to sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Let the driver choose the most efficient method sd.Flags = 0; // To correctly create the swap chain, we must use the IDXGIFactory that was // used to create the device. If we tried to use a different IDXGIFactory instance // (by calling CreateDXGIFactory), we get an error: "IDXGIFactory::CreateSwapChain: // This function is being called with a device from a different IDXGIFactory." IDXGIDevice* dxgiDevice = 0; HR(md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); IDXGIAdapter* dxgiAdapter = 0; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); IDXGIFactory* dxgiFactory = 0; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory)); HR(dxgiFactory->CreateSwapChain(md3dDevice, &sd, &mSwapChain)); // Disables Alt + Enter to toggle between fullscreen and windowed mode //HR(dxgiFactory->MakeWindowAssociation(mhMainWnd, DXGI_MWA_NO_ALT_ENTER)); ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); // The remaining steps that need to be carried out for d3d creation // also need to be executed every time the window is resized. So // just call the OnResize method here to avoid code duplication. OnResize(); return true; }
void GraphicsDevice::Present(void) { HR(m_pSwapChain->Present(m_bUseVSync? 1 : 0,0)); }
void StencilMirrorDemo::drawScene() { HR(gd3dDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, 0xffeeeeee, 1.0f, 0)); HR(gd3dDevice->BeginScene()); HR(mFX->SetTechnique(mhTech)); HR(mFX->SetValue(mhLightVecW, &mLightVecW, sizeof(D3DXVECTOR3))); HR(mFX->SetValue(mhDiffuseLight, &mDiffuseLight, sizeof(D3DXCOLOR))); HR(mFX->SetValue(mhAmbientLight, &mAmbientLight, sizeof(D3DXCOLOR))); HR(mFX->SetValue(mhSpecularLight, &mSpecularLight, sizeof(D3DXCOLOR))); // All objects use the same material. HR(mFX->SetValue(mhAmbientMtrl, &mWhiteMtrl.ambient, sizeof(D3DXCOLOR))); HR(mFX->SetValue(mhDiffuseMtrl, &mWhiteMtrl.diffuse, sizeof(D3DXCOLOR))); HR(mFX->SetValue(mhSpecularMtrl, &mWhiteMtrl.spec, sizeof(D3DXCOLOR))); HR(mFX->SetFloat(mhSpecularPower, mWhiteMtrl.specPower)); drawRoom(); drawMirror(); drawTeapot(); drawReflectedTeapot(); mGfxStats->display(D3DCOLOR_XRGB(0,0,0)); HR(gd3dDevice->EndScene()); HR(gd3dDevice->Present(0, 0, 0, 0)); }
void Shape::DrawScence() { mD3DImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>( &Colors::Silver)); mD3DImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); mD3DImmediateContext->IASetInputLayout(mInputLayout); mD3DImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); mD3DImmediateContext->RSSetState(mWireframeRS); UINT stride = sizeof(Vertex); UINT offset = 0; mD3DImmediateContext->IASetVertexBuffers(0, 1, &mShapeVB, &stride, &offset); mD3DImmediateContext->IASetIndexBuffer(mShapeIB, DXGI_FORMAT_R32_UINT, 0); XMMATRIX view = XMLoadFloat4x4(&mView); XMMATRIX proj = XMLoadFloat4x4(&mProj); XMMATRIX viewProj = view*proj; D3DX11_TECHNIQUE_DESC techDesc; mTech->GetDesc(&techDesc); for ( UINT p = 0; p < techDesc.Passes; ++p ) { // Draw the grid. XMMATRIX world = XMLoadFloat4x4(&mGridWorld); mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj))); mTech->GetPassByIndex(p)->Apply(0, mD3DImmediateContext); mD3DImmediateContext->DrawIndexed(mGridIndexCount, mGridIndexOffset, mGridVertexOffset); // Draw the box. world = XMLoadFloat4x4(&mBoxWorld); mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj))); mTech->GetPassByIndex(p)->Apply(0, mD3DImmediateContext); mD3DImmediateContext->DrawIndexed(mBoxIndexCount, mBoxIndexOffset, mBoxVertexOffset); // Draw center sphere. world = XMLoadFloat4x4(&mCenterSphereWorld); mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj))); mTech->GetPassByIndex(p)->Apply(0, mD3DImmediateContext); mD3DImmediateContext->DrawIndexed(mSphereIndexCount, mSphereIndexOffset, mSphereVertexOffset); // Draw the cylinders. for ( int i = 0; i < 10; ++i ) { world = XMLoadFloat4x4(&mCylinderWorld[i]); mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj))); mTech->GetPassByIndex(p)->Apply(0, mD3DImmediateContext); mD3DImmediateContext->DrawIndexed(mCylinderIndexCount, mCylinderIndexOffset, mCylinderVertexOffset); } // Draw the spheres. for ( int i = 0; i < 10; ++i ) { world = XMLoadFloat4x4(&mSphereWorld[i]); mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj))); mTech->GetPassByIndex(p)->Apply(0, mD3DImmediateContext); mD3DImmediateContext->DrawIndexed(mSphereIndexCount, mSphereIndexOffset, mSphereVertexOffset); } } HR(mSwapChain->Present(0, 0)); }
void StencilMirrorDemo::drawMirror() { HR(mFX->SetMatrix(mhWVP, &(mRoomWorld*mView*mProj))); D3DXMATRIX worldInvTrans; D3DXMatrixInverse(&worldInvTrans, 0, &mRoomWorld); D3DXMatrixTranspose(&worldInvTrans, &worldInvTrans); HR(mFX->SetMatrix(mhWorldInvTrans, &worldInvTrans)); HR(mFX->SetMatrix(mhWorld, &mRoomWorld)); HR(mFX->SetTexture(mhTex, mMirrorTex)); HR(gd3dDevice->SetVertexDeclaration(VertexPNT::Decl)); HR(gd3dDevice->SetStreamSource(0, mRoomVB, 0, sizeof(VertexPNT))); UINT numPasses = 0; HR(mFX->Begin(&numPasses, 0)); for (UINT i = 0; i < numPasses; ++i) { HR(mFX->BeginPass(i)); HR(gd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 18, 2)); HR(mFX->EndPass()); } HR(mFX->End()); }
void Terrain::setDirToSunW(const D3DXVECTOR3& d) { HR(mFX->SetValue(mhDirToSunW, &d, sizeof(D3DXVECTOR3))); }
void StencilMirrorDemo::drawTeapot() { // Cylindrically interpolate texture coordinates HR(gd3dDevice->SetRenderState(D3DRS_WRAP0, D3DWRAPCOORD_0)); HR(mFX->SetMatrix(mhWVP, &(mTeapotWorld*mView*mProj))); D3DXMATRIX worldInvTrans; D3DXMatrixInverse(&worldInvTrans, 0, &mTeapotWorld); D3DXMatrixTranspose(&worldInvTrans, &worldInvTrans); HR(mFX->SetMatrix(mhWorldInvTrans, &worldInvTrans)); HR(mFX->SetMatrix(mhWorld, &mTeapotWorld)); HR(mFX->SetTexture(mhTex, mTeapotTex)); UINT numPasses = 0; HR(mFX->Begin(&numPasses, 0)); for (UINT i = 0; i < numPasses; ++i) { HR(mFX->BeginPass(i)); HR(mTeapot->DrawSubset(0)); HR(mFX->EndPass()); } HR(mFX->End()); HR(gd3dDevice->SetRenderState(D3DRS_WRAP0, 0)); }
void Terrain::buildSubGridMesh(RECT& R, VertexPNT* gridVerts) { //=============================================================== // Get indices for subgrid (we don't use the verts here--the verts // are given by the parameter gridVerts). std::vector<D3DXVECTOR3> tempVerts; std::vector<DWORD> tempIndices; GenTriGrid(SubGrid::NUM_ROWS, SubGrid::NUM_COLS, mDX, mDZ, D3DXVECTOR3(0.0f, 0.0f, 0.0f), tempVerts, tempIndices); ID3DXMesh* subMesh = 0; D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE]; UINT numElems = 0; HR(VertexPNT::Decl->GetDeclaration(elems, &numElems)); HR(D3DXCreateMesh(SubGrid::NUM_TRIS, SubGrid::NUM_VERTS, D3DXMESH_MANAGED, elems, gd3dDevice, &subMesh)); //=============================================================== // Build Vertex Buffer. Copy rectangle of vertices from the // grid into the subgrid structure. VertexPNT* v = 0; HR(subMesh->LockVertexBuffer(0, (void**)&v)); int k = 0; for(int i = R.top; i <= R.bottom; ++i) { for(int j = R.left; j <= R.right; ++j) { v[k++] = gridVerts[i*mVertCols+j]; } } //=============================================================== // Compute the bounding box before unlocking the vertex buffer. AABB bndBox; HR(D3DXComputeBoundingBox((D3DXVECTOR3*)v, subMesh->GetNumVertices(), sizeof(VertexPNT), &bndBox.minPt, &bndBox.maxPt)); HR(subMesh->UnlockVertexBuffer()); //=============================================================== // Build Index and Attribute Buffer. WORD* indices = 0; DWORD* attBuff = 0; HR(subMesh->LockIndexBuffer(0, (void**)&indices)); HR(subMesh->LockAttributeBuffer(0, &attBuff)); for(int i = 0; i < SubGrid::NUM_TRIS; ++i) { indices[i*3+0] = (WORD)tempIndices[i*3+0]; indices[i*3+1] = (WORD)tempIndices[i*3+1]; indices[i*3+2] = (WORD)tempIndices[i*3+2]; attBuff[i] = 0; // All in subset 0. } HR(subMesh->UnlockIndexBuffer()); HR(subMesh->UnlockAttributeBuffer()); //=============================================================== // Optimize for the vertex cache and build attribute table. DWORD* adj = new DWORD[subMesh->GetNumFaces()*3]; HR(subMesh->GenerateAdjacency(EPSILON, adj)); HR(subMesh->OptimizeInplace(D3DXMESHOPT_VERTEXCACHE|D3DXMESHOPT_ATTRSORT, adj, 0, 0, 0)); delete[] adj; //=============================================================== // Save the mesh and bounding box. mSubGridMeshes.push_back(subMesh); mSubGridBndBoxes.push_back(bndBox); }
void StencilMirrorDemo::drawReflectedTeapot() { HR(gd3dDevice->SetRenderState(D3DRS_STENCILENABLE, true)); HR(gd3dDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS)); HR(gd3dDevice->SetRenderState(D3DRS_STENCILREF, 0x1)); HR(gd3dDevice->SetRenderState(D3DRS_STENCILMASK, 0xffffffff)); HR(gd3dDevice->SetRenderState(D3DRS_STENCILWRITEMASK, 0xffffffff)); HR(gd3dDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP)); HR(gd3dDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP)); HR(gd3dDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE)); // Disable writes to the depth and back buffers HR(gd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, false)); HR(gd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true)); HR(gd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO)); HR(gd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE)); // Draw mirror to stencil only drawMirror(); // Re-eanble depth writes HR(gd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, true)); // Only draw reflected teapot to the pixels where the mirror was drawn to. HR(gd3dDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_EQUAL)); HR(gd3dDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP)); // Build Reflection transformation. D3DXMATRIX R; D3DXPLANE plane(0.0f, 0.0f, 1.0f, 0.0f); // xy plane D3DXMatrixReflect(&R, &plane); // Save the original teapot world matrix. D3DXMATRIX oldTeapotWorld = mTeapotWorld; // Add reflection transform. mTeapotWorld = mTeapotWorld * R; // Reflect light vector also. D3DXVECTOR3 oldLightVecW = mLightVecW; D3DXVec3TransformNormal(&mLightVecW, &mLightVecW, &R); HR(mFX->SetValue(mhLightVecW, &mLightVecW, sizeof(D3DXVECTOR3))); // Disable depth buffer and render the reflected teapot. HR(gd3dDevice->SetRenderState(D3DRS_ZENABLE, false)); HR(gd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false)); // Finally, draw the reflected teapot HR(gd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW)); drawTeapot(); mTeapotWorld = oldTeapotWorld; mLightVecW = oldLightVecW; // Restore render states. HR(gd3dDevice->SetRenderState(D3DRS_ZENABLE, true)); HR(gd3dDevice->SetRenderState(D3DRS_STENCILENABLE, false)); HR(gd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW)); }
void Terrain::onResetDevice() { HR(mFX->OnResetDevice()); }
bool D3DApp::InitDirect3D() { // Begin to create device and swap chains UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL FeatureLevelsRequested = D3D_FEATURE_LEVEL_11_0; UINT numLevelsRequested = 1; D3D_FEATURE_LEVEL FeatureLevelsSupported; // create a struct to hold information about the swap chain DXGI_SWAP_CHAIN_DESC swapChainDesc; // clear out the struct for use ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // fill the swap chain description struct swapChainDesc.BufferDesc.Width = m_clientWidth; swapChainDesc.BufferDesc.Height = m_clientHeight; swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; if (m_enable4xMsaa) { swapChainDesc.SampleDesc.Count = 4; swapChainDesc.SampleDesc.Quality = m_4xMsaaQuality - 1; } else { swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; } swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 1; swapChainDesc.OutputWindow = window; swapChainDesc.Windowed = true; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; hr = D3D11CreateDeviceAndSwapChain( 0, // Default 0 Adapter D3D_DRIVER_TYPE_HARDWARE, // Driver Type NULL, // Software createDeviceFlags, // Flags &FeatureLevelsRequested, // Feature Levels Requested Pointer 1, // Number of Feature Levels D3D11_SDK_VERSION, // D3D11_SDK_VERSION &swapChainDesc, // Swap Chain Desciptions &m_swapChain, // Swap Chain Pointer &m_d3dDevice, // D3D Device &FeatureLevelsSupported, // Return supported levels &m_d3dImmediateContext // Device Context Pointer ); if ( FAILED(hr) ) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } if (FeatureLevelsSupported != D3D_FEATURE_LEVEL_11_0) { MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0); return false; } HR(m_d3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_4xMsaaQuality)); assert(m_4xMsaaQuality > 0); OnResize(); return true; }
void RenderStates::InitAll(ID3D11Device* device) { // // WireframeRS // D3D11_RASTERIZER_DESC wireframeDesc; ZeroMemory(&wireframeDesc, sizeof(D3D11_RASTERIZER_DESC)); wireframeDesc.FillMode = D3D11_FILL_WIREFRAME; wireframeDesc.CullMode = D3D11_CULL_BACK; wireframeDesc.FrontCounterClockwise = false; wireframeDesc.DepthClipEnable = true; HR(device->CreateRasterizerState(&wireframeDesc, &WireframeRS)); // // NoCullRS // D3D11_RASTERIZER_DESC noCullDesc; ZeroMemory(&noCullDesc, sizeof(D3D11_RASTERIZER_DESC)); noCullDesc.FillMode = D3D11_FILL_SOLID; noCullDesc.CullMode = D3D11_CULL_NONE; noCullDesc.FrontCounterClockwise = false; noCullDesc.DepthClipEnable = true; HR(device->CreateRasterizerState(&noCullDesc, &NoCullRS)); // // CullClockwiseRS // // Note: Define such that we still cull backfaces by making front faces CCW. // If we did not cull backfaces, then we have to worry about the BackFace // property in the D3D11_DEPTH_STENCIL_DESC. D3D11_RASTERIZER_DESC cullClockwiseDesc; ZeroMemory(&cullClockwiseDesc, sizeof(D3D11_RASTERIZER_DESC)); cullClockwiseDesc.FillMode = D3D11_FILL_SOLID; cullClockwiseDesc.CullMode = D3D11_CULL_BACK; cullClockwiseDesc.FrontCounterClockwise = true; cullClockwiseDesc.DepthClipEnable = true; HR(device->CreateRasterizerState(&cullClockwiseDesc, &CullClockwiseRS)); // // AlphaToCoverageBS // D3D11_BLEND_DESC alphaToCoverageDesc = {0}; alphaToCoverageDesc.AlphaToCoverageEnable = true; alphaToCoverageDesc.IndependentBlendEnable = false; alphaToCoverageDesc.RenderTarget[0].BlendEnable = false; alphaToCoverageDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; HR(device->CreateBlendState(&alphaToCoverageDesc, &AlphaToCoverageBS)); // // TransparentBS // D3D11_BLEND_DESC transparentDesc = {0}; transparentDesc.AlphaToCoverageEnable = false; transparentDesc.IndependentBlendEnable = false; transparentDesc.RenderTarget[0].BlendEnable = true; transparentDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; transparentDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; transparentDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; transparentDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; transparentDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; transparentDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; transparentDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; HR(device->CreateBlendState(&transparentDesc, &TransparentBS)); // // NoRenderTargetWritesBS // D3D11_BLEND_DESC noRenderTargetWritesDesc = {0}; noRenderTargetWritesDesc.AlphaToCoverageEnable = false; noRenderTargetWritesDesc.IndependentBlendEnable = false; noRenderTargetWritesDesc.RenderTarget[0].BlendEnable = false; noRenderTargetWritesDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; noRenderTargetWritesDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO; noRenderTargetWritesDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; noRenderTargetWritesDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; noRenderTargetWritesDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; noRenderTargetWritesDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; noRenderTargetWritesDesc.RenderTarget[0].RenderTargetWriteMask = 0; HR(device->CreateBlendState(&noRenderTargetWritesDesc, &NoRenderTargetWritesBS)); // // MarkMirrorDSS // D3D11_DEPTH_STENCIL_DESC mirrorDesc; mirrorDesc.DepthEnable = true; mirrorDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; mirrorDesc.DepthFunc = D3D11_COMPARISON_LESS; mirrorDesc.StencilEnable = true; mirrorDesc.StencilReadMask = 0xff; mirrorDesc.StencilWriteMask = 0xff; mirrorDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; mirrorDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; mirrorDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_REPLACE; mirrorDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // We are not rendering backfacing polygons, so these settings do not matter. mirrorDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; mirrorDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; mirrorDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_REPLACE; mirrorDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; HR(device->CreateDepthStencilState(&mirrorDesc, &MarkMirrorDSS)); // // DrawReflectionDSS // D3D11_DEPTH_STENCIL_DESC drawReflectionDesc; drawReflectionDesc.DepthEnable = true; drawReflectionDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; drawReflectionDesc.DepthFunc = D3D11_COMPARISON_LESS; drawReflectionDesc.StencilEnable = true; drawReflectionDesc.StencilReadMask = 0xff; drawReflectionDesc.StencilWriteMask = 0xff; drawReflectionDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; drawReflectionDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; drawReflectionDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; drawReflectionDesc.FrontFace.StencilFunc = D3D11_COMPARISON_EQUAL; // We are not rendering backfacing polygons, so these settings do not matter. drawReflectionDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; drawReflectionDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; drawReflectionDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; drawReflectionDesc.BackFace.StencilFunc = D3D11_COMPARISON_EQUAL; HR(device->CreateDepthStencilState(&drawReflectionDesc, &DrawReflectionDSS)); // // NoDoubleBlendDSS // D3D11_DEPTH_STENCIL_DESC noDoubleBlendDesc; noDoubleBlendDesc.DepthEnable = true; noDoubleBlendDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; noDoubleBlendDesc.DepthFunc = D3D11_COMPARISON_LESS; noDoubleBlendDesc.StencilEnable = true; noDoubleBlendDesc.StencilReadMask = 0xff; noDoubleBlendDesc.StencilWriteMask = 0xff; noDoubleBlendDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; noDoubleBlendDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; noDoubleBlendDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_INCR; noDoubleBlendDesc.FrontFace.StencilFunc = D3D11_COMPARISON_EQUAL; // We are not rendering backfacing polygons, so these settings do not matter. noDoubleBlendDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; noDoubleBlendDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; noDoubleBlendDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_INCR; noDoubleBlendDesc.BackFace.StencilFunc = D3D11_COMPARISON_EQUAL; HR(device->CreateDepthStencilState(&noDoubleBlendDesc, &NoDoubleBlendDSS)); }
void D3DApp::OnResize() { assert(md3dImmediateContext); assert(md3dDevice); assert(mSwapChain); // Release the old views, as they hold references to the buffers we // will be destroying. Also release the old depth/stencil buffer. ReleaseCOM(mRenderTargetView); ReleaseCOM(mDepthStencilView); ReleaseCOM(mDepthStencilBuffer); // Resize the swap chain and recreate the render target view. HR(mSwapChain->ResizeBuffers(1, mClientWidth, mClientHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0)); ID3D11Texture2D* backBuffer; HR(mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer))); HR(md3dDevice->CreateRenderTargetView(backBuffer, 0, &mRenderTargetView)); ReleaseCOM(backBuffer); // Create the depth/stencil buffer and view. D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = mClientWidth; depthStencilDesc.Height = mClientHeight; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; // Use 4X MSAA? --must match swap chain MSAA values. if( mEnable4xMsaa ) { depthStencilDesc.SampleDesc.Count = 4; depthStencilDesc.SampleDesc.Quality = m4xMsaaQuality-1; } // No MSAA else { depthStencilDesc.SampleDesc.Count = 1; depthStencilDesc.SampleDesc.Quality = 0; } depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; HR(md3dDevice->CreateTexture2D(&depthStencilDesc, 0, &mDepthStencilBuffer)); HR(md3dDevice->CreateDepthStencilView(mDepthStencilBuffer, 0, &mDepthStencilView)); // Bind the render target view and depth/stencil view to the pipeline. md3dImmediateContext->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView); // Set the viewport transform. mScreenViewport.TopLeftX = 0; mScreenViewport.TopLeftY = 0; mScreenViewport.Width = static_cast<float>(mClientWidth); mScreenViewport.Height = static_cast<float>(mClientHeight); mScreenViewport.MinDepth = 0.0f; mScreenViewport.MaxDepth = 1.0f; md3dImmediateContext->RSSetViewports(1, &mScreenViewport); }
void WaterDemo::drawScene() { HR(gd3dDevice->BeginScene()); mSky->draw(); HR(mFX->SetValue(mhLight, &mLight, sizeof(DirLight))); HR(mFX->SetMatrix(mhWVP, &(mSceneWorld*gCamera->viewProj()))); HR(mFX->SetValue(mhEyePosW, &gCamera->pos(), sizeof(D3DXVECTOR3))); UINT numPasses = 0; HR(mFX->Begin(&numPasses, 0)); HR(mFX->BeginPass(0)); for(UINT j = 0; j < mSceneMtrls.size(); ++j) { HR(mFX->SetValue(mhMtrl, &mSceneMtrls[j], sizeof(Mtrl))); // If there is a texture, then use. if(mSceneTextures[j] != 0) { HR(mFX->SetTexture(mhTex, mSceneTextures[j])); } // But if not, then set a pure white texture. When the texture color // is multiplied by the color from lighting, it is like multiplying by // 1 and won't change the color from lighting. else { HR(mFX->SetTexture(mhTex, mWhiteTex)); } HR(mFX->SetTexture(mhNormalMap, mSceneNormalMaps[j])); HR(mFX->CommitChanges()); HR(mSceneMesh->DrawSubset(j)); } HR(mFX->EndPass()); HR(mFX->End()); // Draw alpha blended object last. mWater->draw(); mGfxStats->display(); HR(gd3dDevice->EndScene()); // Present the backbuffer. HR(gd3dDevice->Present(0, 0, 0, 0)); }
bool D3DApp::InitDirect3D() { // Create the device and device context. UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; HRESULT hr = D3D11CreateDevice( 0, // default adapter md3dDriverType, 0, // no software device createDeviceFlags, 0, 0, // default feature level array D3D11_SDK_VERSION, &md3dDevice, &featureLevel, &md3dImmediateContext); if( FAILED(hr) ) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } if( featureLevel != D3D_FEATURE_LEVEL_11_0 ) { MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0); return false; } // Check 4X MSAA quality support for our back buffer format. // All Direct3D 11 capable devices support 4X MSAA for all render // target formats, so we only need to check quality support. HR(md3dDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality)); assert( m4xMsaaQuality > 0 ); // Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain. DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = mClientWidth; sd.BufferDesc.Height = mClientHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Use 4X MSAA? if( mEnable4xMsaa ) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m4xMsaaQuality-1; } // No MSAA else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = mhMainWnd; sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; // To correctly create the swap chain, we must use the IDXGIFactory that was // used to create the device. If we tried to use a different IDXGIFactory instance // (by calling CreateDXGIFactory), we get an error: "IDXGIFactory::CreateSwapChain: // This function is being called with a device from a different IDXGIFactory." IDXGIDevice* dxgiDevice = 0; HR(md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); IDXGIAdapter* dxgiAdapter = 0; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); IDXGIFactory* dxgiFactory = 0; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory)); HR(dxgiFactory->CreateSwapChain(md3dDevice, &sd, &mSwapChain)); ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); // The remaining steps that need to be carried out for d3d creation // also need to be executed every time the window is resized. So // just call the OnResize method here to avoid code duplication. OnResize(); return true; }
GeoBuffer() { for (int y = 0; y < Md.height; y++) { for (int x = 0; x < Md.width; x++) { float ID = (float)Md.grid[x][y][0] - 1; float col = floor(ID / 52.0f); float row = ID - (col * 52.0f); float sx = 1.0f / 52.0f; float sy = 1.0f / 52.0f; XMMATRIX trans = XMMatrixTranslation(row, col, 0.0f); XMMATRIX scale = XMMatrixScaling(sx, sy, 1.0f); XMStoreFloat4x4(&mTexTransform[x + (y * Md.width)], trans * scale); GeometryGenerator::MeshData box; GeometryGenerator geoGen; //geoGen.CreateBox(1.0f, 1.0f, 1.0f, box); //geoGen.CreateFullscreenQuad(box); //Works //geoGen.CreateGrid(2.0f, 2.0f, 10, 10, box); //geoGen.CreateGeosphere(0.75f, 100, box); geoGen.CreateSquare(x, y, box); // Cache the vertex offsets to each object in the concatenated vertex buffer. mBoxVertexOffset = 0; // Cache the index count of each object. mBoxIndexCount = box.Indices.size(); // Cache the starting index for each object in the concatenated index buffer. mBoxIndexOffset = 0; //UINT totalVertexCount = box.Vertices.size(); UINT totalVertexCount = box.Vertices.size(); UINT totalIndexCount = mBoxIndexCount; // // Extract the vertex elements we are interested in and pack the // vertices of all the meshes into one vertex buffer. // std::vector<Vertex::Basic32> vertices(totalVertexCount); UINT k = 0; for (size_t i = 0; i < box.Vertices.size(); ++i, ++k) { vertices[k].Pos = box.Vertices[i].Position; vertices[k].Normal = box.Vertices[i].Normal; vertices[k].Tex = box.Vertices[i].TexC; } D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex::Basic32) * totalVertexCount; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vertices[0]; HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mBoxVB[x + (y * Md.width)])); // // Pack the indices of all the meshes into one index buffer. // std::vector<UINT> indices; indices.insert(indices.end(), box.Indices.begin(), box.Indices.end()); D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT) * totalIndexCount; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &indices[0]; HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mBoxIB[x + (y * Md.width)])); } } }
void MirrorApp::BuildSkullGeometryBuffers() { std::ifstream fin("Models/skull.txt"); if(!fin) { MessageBox(0, L"Models/skull.txt not found.", 0, 0); return; } UINT vcount = 0; UINT tcount = 0; std::string ignore; fin >> ignore >> vcount; fin >> ignore >> tcount; fin >> ignore >> ignore >> ignore >> ignore; std::vector<Vertex::Basic32> vertices(vcount); for(UINT i = 0; i < vcount; ++i) { fin >> vertices[i].Pos.x >> vertices[i].Pos.y >> vertices[i].Pos.z; fin >> vertices[i].Normal.x >> vertices[i].Normal.y >> vertices[i].Normal.z; } fin >> ignore; fin >> ignore; fin >> ignore; mSkullIndexCount = 3*tcount; std::vector<UINT> indices(mSkullIndexCount); for(UINT i = 0; i < tcount; ++i) { fin >> indices[i*3+0] >> indices[i*3+1] >> indices[i*3+2]; } fin.close(); D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex::Basic32) * vcount; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vertices[0]; HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mSkullVB)); // // Pack the indices of all the meshes into one index buffer. // D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT) * mSkullIndexCount; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &indices[0]; HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mSkullIB)); }