void DemoApp::DrawScene() { assert(md3dImmediateContext); assert(mSwapChain); //Render shadow map m_pShadowMap->BindShadowMapDSV(md3dImmediateContext); RenderShadowMap(); m_pDepthSRV = m_pShadowMap->DepthShaderResourceView(); //Restore render targets md3dImmediateContext->RSSetState(0); ID3D11RenderTargetView* renderTargets[1] = { mRenderTargetView }; md3dImmediateContext->OMSetRenderTargets(1, renderTargets, mDepthStencilView); md3dImmediateContext->RSSetViewports(1, &mScreenViewport); //Clear Render Targets float clearColor[4] = { 199.0f / 255.0f, 197.0f / 255.0f, 206.0f / 255.0f, 1.0f }; md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, clearColor); md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); //Set Render State md3dImmediateContext->RSSetState(RenderStates::CullClockwiseRS); //Set Vertex and Index Buffers UINT strides[2] = { sizeof(Vertex::VertexPNT), sizeof(Vertex::VertexIns_Mat) }; UINT offsets[2] = { 0, 0 }; ID3D11Buffer * buffers[2] = { m_pVertexBuffer, m_pInstancedBuffer }; md3dImmediateContext->IASetVertexBuffers(0, 2, buffers, strides, offsets); md3dImmediateContext->IASetIndexBuffer(m_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0); //Update Per Object Constant Buffer CBPerObject cbPerObj; cbPerObj.matWorld = XMMatrixTranspose(mWorld); cbPerObj.matWorldInvTranspose = XMMatrixTranspose(MathHelper::InverseTranspose(mWorld)); cbPerObj.matWVP = XMMatrixTranspose(mWorld * m_pCamera->GetViewProjMatrix()); cbPerObj.matLightWVPT = XMMatrixTranspose(mWorld * mLightVPT); cbPerObj.isInstancing = 1; cbPerObj.material.Ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); cbPerObj.material.Diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f); cbPerObj.material.Specular = XMFLOAT4(0.1f, 0.1f, 0.1f, 1.0f); cbPerObj.material.Reflect = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f); md3dImmediateContext->UpdateSubresource(m_pCBPerObject, 0, NULL, &cbPerObj, 0, 0); //Set Shaders and Resources md3dImmediateContext->VSSetShader(m_pVertexShader, NULL, 0); md3dImmediateContext->VSSetConstantBuffers(3, 1, &m_pCBPerObject); md3dImmediateContext->PSSetShader(m_pPixelShader, NULL, 0); md3dImmediateContext->PSSetConstantBuffers(3, 1, &m_pCBPerObject); md3dImmediateContext->PSSetShaderResources(0, 1, &m_pPillarSRV); md3dImmediateContext->PSSetShaderResources(2, 1, &m_pDepthSRV); md3dImmediateContext->PSSetSamplers(0, 1, &m_pSampleLinear); md3dImmediateContext->PSSetSamplers(1, 1, &m_pSampleShadowMap); //Draw Pillars md3dImmediateContext->DrawIndexedInstanced(36, instanceCnt, 0, 0, 0); UINT stride = sizeof(Vertex::VertexPNT); UINT offset = 0; md3dImmediateContext->IASetVertexBuffers(0, 1, &m_pGroundVertexBuffer, &stride, &offset); md3dImmediateContext->IASetIndexBuffer(m_pGroundIndexBuffer, DXGI_FORMAT_R32_UINT, 0); cbPerObj.isInstancing = 0; md3dImmediateContext->UpdateSubresource(m_pCBPerObject, 0, NULL, &cbPerObj, 0, 0); md3dImmediateContext->PSSetShaderResources(0, 1, &m_pGroundSRV); //Draw Ground md3dImmediateContext->DrawIndexed(36, 0, 0); //Draw Skybox m_pSkybox->Draw(md3dImmediateContext, m_pCamera); md3dImmediateContext->RSSetState(0); md3dImmediateContext->OMSetDepthStencilState(0, 0); //Render mini window displaying shadow map RenderMiniWindow(); HR(mSwapChain->Present(0, 0)); }
void WavesApp::BuildLandGeometryBuffers() { GeometryGenerator::MeshData grid; GeometryGenerator geoGen; geoGen.CreateGrid(160.f, 160.f, 50, 50, grid); m_uLandGridIndexCount = grid.Indices.size(); // // Extract the vertex elements we are interested and apply the height function // to each vertex. In addition,color the vertices based on their so we have // sandy looking beaches,grassy low hills,and snow moutain peaks // std::vector<Vertex> vertices(grid.Vertices.size()); for (size_t i = 0; i < grid.Vertices.size(); ++i) { XMFLOAT3 p = grid.Vertices[i].Position; p.y = GetHeight(p.x, p.z); vertices[i].Pos = p; if (p.y < -10.f) { //Sandy beach color vertices[i].Color = XMFLOAT4(1.0f,0.96f,0.62f,1.0f); } else if (p.y < 5.0f) { // Light yellow-green. vertices[i].Color = XMFLOAT4(0.48f, 0.77f, 0.46f, 1.0f); } else if (p.y < 12.0f) { // Dark yellow-green. vertices[i].Color = XMFLOAT4(0.1f, 0.48f, 0.19f, 1.0f); } else if (p.y < 20.0f) { // Dark brown. vertices[i].Color = XMFLOAT4(0.45f, 0.39f, 0.34f, 1.0f); } else { // White snow. vertices[i].Color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); } } { D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE;//jingz todo 为什么CPU要访问和修改?? vbd.ByteWidth = sizeof(Vertex) * vertices.size(); vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; vbd.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA initDate; initDate.pSysMem = &vertices[0]; HR(m_pD3dDevice->CreateBuffer(&vbd, &initDate,&m_pLandVB)); } { D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE;//jingz todo 为什么CPU要访问和修改?? ibd.ByteWidth = sizeof(UINT) * m_uLandGridIndexCount; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; ibd.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA initDate; initDate.pSysMem = &grid.Indices[0]; HR(m_pD3dDevice->CreateBuffer(&ibd, &initDate, &m_pLandIB)); } }
//-------------------------------------------------------------------------------------- // Direct3Dデバイスとスワップチェーン //-------------------------------------------------------------------------------------- HRESULT InitDevice() { HRESULT hr = S_OK; UINT createDeviceFlags = 0; //ドライバタイプの定義 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, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; UINT numFeatureLevels = ARRAYSIZE( featureLevels ); //スワップチェーンの設定 DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = HMDDesc.Resolution.w; sd.BufferDesc.Height = HMDDesc.Resolution.h; 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; //Direct3Dデバイスの作成とスワップチェーンの作成 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; //レンダーターゲットビュー 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; //深度バッファ作成(ステンシル) 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; //ステンシルビューの作成 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 ); //ビューポートの設定 D3D11_VIEWPORT vp; vp.Width = (FLOAT)HMDDesc.Resolution.w; vp.Height = (FLOAT)HMDDesc.Resolution.h; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; g_pImmediateContext->RSSetViewports( 1, &vp ); //頂点シェーダーをコンパイル ID3DBlob* pVSBlob = NULL; hr = CompileShaderFromFile( "SimpleShader.hlsl", "VS", "vs_4_0", &pVSBlob ); if( FAILED( hr ) ) { MessageBox( NULL,"頂点シェーダーを読み込めませんでした。", "Error", MB_OK ); return hr; } //頂点シェーダーから頂点シェーダのオブジェクトを作成 hr = g_pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader ); if( FAILED( hr ) ) { pVSBlob->Release(); return hr; } //頂点のインプットレイアウトを定義 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 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE( layout ); //インプットレイアウトの作成 hr = g_pd3dDevice->CreateInputLayout( layout, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &g_pVertexLayout ); pVSBlob->Release();pVSBlob = NULL; if( FAILED( hr ) ) return hr; //インプットレイアウトのセット g_pImmediateContext->IASetInputLayout( g_pVertexLayout ); //ピクセルシェーダーをコンパイル ID3DBlob* pPSBlob = NULL; hr = CompileShaderFromFile("SimpleShader.hlsl", "PS", "ps_4_0", &pPSBlob ); if( FAILED( hr ) ) { MessageBox( NULL,"頂点シェーダーを読み込めませんでした。", "Error", MB_OK ); return hr; } //ピクセルシェーダーからピクセルシェーダのオブジェクトを作成 hr = g_pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShader ); pPSBlob->Release(); if( FAILED( hr ) ) return hr; //頂点バッファの作成 SimpleVertex vertices[] = { { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT4( 1.0f, 0.0f, 0.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT4( 0.0f, 0.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT4( 0.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT4( 0.5f, 0.5f, 0.5f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT4( 0.5f, 0.5f, 0.5f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.5f, 0.5f, 0.5f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.5f, 0.5f, 0.5f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT4( 1.0f, 0.0f, 0.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT4( 0.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 0.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, }; D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof(bd) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( SimpleVertex ) * 24; 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; //インデックスバッファの作成 WORD indices[] = { 3,1,0, 2,1,3, 6,4,5, 7,4,6, 11,9,8, 10,9,11, 14,12,13, 15,12,14, 19,17,16, 18,17,19, 22,20,21, 23,20,22 }; bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( WORD ) * 36; // 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; // コンスタントバッファの作成 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; //画像をテクスチャにロード hr = D3DX11CreateShaderResourceViewFromFile( g_pd3dDevice, "suwako.png", NULL, NULL, &g_pTextureRV, NULL ); if( FAILED( hr ) ) return hr; //サンプラーステートの作成 D3D11_SAMPLER_DESC sampDesc; ZeroMemory( &sampDesc, sizeof(sampDesc) ); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; hr = g_pd3dDevice->CreateSamplerState( &sampDesc, &g_pSamplerLinear ); if( FAILED( hr ) ) return hr; //行列の設定 // ワールド行列は単位行列 g_World = XMMatrixIdentity(); //ビュー行列の定義 XMVECTOR Eye = XMVectorSet( 0.0f, 1.0f, -5.0f, 0.0f ); //カメラの位置 XMVECTOR At = XMVectorSet( 0.0f, 0.0f, 0.0f, 0.0f ); //カメラの注視先 XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ); //カメラの真上のベクトル g_View = XMMatrixLookAtLH( Eye, At, Up ); //プロジェクション行列 g_Projection = XMMatrixPerspectiveFovLH( XM_PIDIV2, WIDTH / (FLOAT)HEIGHT, 0.01f, 100.0f ); return S_OK; }
void ModelLoader::CreateVertexBuffer( Vertex::VERTEX_TYPE type ) { aiMesh* mesh = scene->mMeshes[0]; UINT count = mesh->mNumVertices; aiVector3D* vertices = mesh->mVertices; /* The switch case looks like duplicated code. It is not. vertData is a different type in each and SetVertices() is a template. */ switch( type ) { case Vertex::BASIC_32: { std::vector<Vertex::Basic32> vertData( count ); aiVector3D* normals = mesh->mNormals; aiVector3D* texCoords = mesh->mTextureCoords[0]; for( UINT i = 0; i<count; ++i ) { UpdateExtents( vertices[i].x, vertices[i].y, vertices[i].z ); vertData[i].Pos = XMFLOAT3( vertices[i].x, vertices[i].y, vertices[i].z ); vertData[i].Normal = XMFLOAT3( normals[i].x, normals[i].y, normals[i].z ); vertData[i].Tex = XMFLOAT2( texCoords[i].x, texCoords[i].y ); } SetVertices( device, count, vertData.data() ); break; } case Vertex::POS_NORMAL_TEX_TAN: { aiVector3D* normals = mesh->mNormals; aiVector3D* texCoords = mesh->mTextureCoords[0]; aiVector3D* tangents = mesh->mTangents; std::vector<Vertex::PosNormalTexTan> vertData( count ); for( UINT i = 0; i<count; ++i ) { UpdateExtents( vertices[i].x, vertices[i].y, vertices[i].z ); vertData[i].Pos = XMFLOAT3( vertices[i].x, vertices[i].y, vertices[i].z ); vertData[i].Normal = XMFLOAT3( normals[i].x, normals[i].y, normals[i].z ); vertData[i].Tex = XMFLOAT2( texCoords[i].x, texCoords[i].y ); vertData[i].TangentU = XMFLOAT4( tangents[i].x, tangents[i].y, tangents[i].z, 0.f ); } SetVertices( device, count, vertData.data() ); break; } case Vertex::POS_NORMAL_TEX_TAN_SKINNED: { aiVector3D* normals = mesh->mNormals; aiVector3D* texCoords = mesh->mTextureCoords[0]; aiVector3D* tangents = mesh->mTangents; std::vector<Vertex::PosNormalTexTanSkinned> vertData( count ); for( UINT i = 0; i<count; ++i ) { UpdateExtents( vertices[i].x, vertices[i].y, vertices[i].z ); vertData[i].Pos = XMFLOAT3( vertices[i].x, vertices[i].y, vertices[i].z ); vertData[i].Normal = XMFLOAT3( normals[i].x, normals[i].y, normals[i].z ); vertData[i].Tex = XMFLOAT2( texCoords[i].x, texCoords[i].y ); vertData[i].TangentU = XMFLOAT4( tangents[i].x, tangents[i].y, tangents[i].z, 0.f ); } // Bone Data std::multimap<int, BoneWeight> vertexBoneWeight; for( unsigned int boneIndex = 0; boneIndex<mesh->mNumBones; ++boneIndex ) { auto bone = mesh->mBones[boneIndex]; for( int i = 0; i<bone->mNumWeights; ++i ) { auto boneWeight = BoneWeight( boneIndex, bone->mWeights[i].mWeight ); vertexBoneWeight.insert( std::pair<int, BoneWeight>( bone->mWeights[i].mVertexId, boneWeight ) ); } } for( UINT i = 0; i<count; ++i ) { BYTE boneIndices[4] = { 0, 0, 0, 0 }; float weights[4] = { 0, 0, 0, 0 }; int j = 0; auto itlow = vertexBoneWeight.lower_bound( i ); auto itup = vertexBoneWeight.upper_bound( i ); assert( itlow!=itup ); // every vertex should have some influence for( auto it = itlow; it!=itup; ++it ) { if( j>3 ) { assert( false ); // only 4 boes should influence one vertex break; } boneIndices[j] = it->second.boneIndex; weights[j] = it->second.weight; ++j; } vertData[i].BoneIndicies[0] = boneIndices[0]; vertData[i].BoneIndicies[1] = boneIndices[1]; vertData[i].BoneIndicies[2] = boneIndices[2]; vertData[i].BoneIndicies[3] = boneIndices[3]; vertData[i].Weights = XMFLOAT4( weights ); } SetVertices( device, count, vertData.data() ); break; } } }
XMFLOAT4 Lerp(const XMFLOAT4& a, const XMFLOAT4& b, float i) { return XMFLOAT4(Lerp(a.x, b.x, i), Lerp(a.y, b.y, i), Lerp(a.z, b.z, i), Lerp(a.w, b.w, i)); }
void DiffuseLight::setDiffuseColor(float red, float green, float blue, float alpha) { diffuseColor = XMFLOAT4(red, green, blue, alpha); }
// Load the sample assets. void D3D12HeterogeneousMultiadapter::LoadAssets() { // Create the root signatures. { CD3DX12_ROOT_PARAMETER rootParameters[2]; rootParameters[0].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_VERTEX); rootParameters[1].InitAsConstantBufferView(1, 0, D3D12_SHADER_VISIBILITY_PIXEL); CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc; rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); ComPtr<ID3DBlob> signature; ComPtr<ID3DBlob> error; ThrowIfFailed(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error)); ThrowIfFailed(m_devices[Primary]->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&m_rootSignature))); CD3DX12_DESCRIPTOR_RANGE ranges[1]; ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); CD3DX12_ROOT_PARAMETER blurRootParameters[3]; blurRootParameters[0].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_PIXEL); blurRootParameters[1].InitAsDescriptorTable(_countof(ranges), ranges, D3D12_SHADER_VISIBILITY_PIXEL); blurRootParameters[2].InitAsConstantBufferView(1, 0, D3D12_SHADER_VISIBILITY_PIXEL); CD3DX12_STATIC_SAMPLER_DESC staticPointSampler(0); staticPointSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; staticPointSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; CD3DX12_STATIC_SAMPLER_DESC staticLinearSampler(1); staticLinearSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; staticLinearSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; D3D12_STATIC_SAMPLER_DESC staticSamplers[] = { staticPointSampler, staticLinearSampler }; rootSignatureDesc.Init(_countof(blurRootParameters), blurRootParameters, _countof(staticSamplers), staticSamplers, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); ThrowIfFailed(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error)); ThrowIfFailed(m_devices[Secondary]->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&m_blurRootSignature))); } // Create the pipeline states, which includes compiling and loading shaders. { ComPtr<ID3DBlob> vertexShader; ComPtr<ID3DBlob> pixelShader; ComPtr<ID3DBlob> vertexShaderBlur; ComPtr<ID3DBlob> pixelShaderBlurU; ComPtr<ID3DBlob> pixelShaderBlurV; ComPtr<ID3DBlob> error; #if defined(_DEBUG) // Enable better shader debugging with the graphics debugging tools. UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; #else UINT compileFlags = 0; #endif ThrowIfFailed(D3DCompileFromFile(GetAssetFullPath(L"shaders.hlsl").c_str(), nullptr, nullptr, "VShader", "vs_5_0", compileFlags, 0, &vertexShader, &error)); ThrowIfFailed(D3DCompileFromFile(GetAssetFullPath(L"shaders.hlsl").c_str(), nullptr, nullptr, "PShader", "ps_5_0", compileFlags, 0, &pixelShader, &error)); ThrowIfFailed(D3DCompileFromFile(GetAssetFullPath(L"blurShaders.hlsl").c_str(), nullptr, nullptr, "VSSimpleBlur", "vs_5_0", compileFlags, 0, &vertexShaderBlur, &error)); ThrowIfFailed(D3DCompileFromFile(GetAssetFullPath(L"blurShaders.hlsl").c_str(), nullptr, nullptr, "PSSimpleBlurU", "ps_5_0", compileFlags, 0, &pixelShaderBlurU, &error)); ThrowIfFailed(D3DCompileFromFile(GetAssetFullPath(L"blurShaders.hlsl").c_str(), nullptr, nullptr, "PSSimpleBlurV", "ps_5_0", compileFlags, 0, &pixelShaderBlurV, &error)); // Define the vertex input layouts. const D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; const D3D12_INPUT_ELEMENT_DESC blurInputElementDescs[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; // Describe and create the graphics pipeline state objects (PSOs). D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) }; psoDesc.pRootSignature = m_rootSignature.Get(); psoDesc.VS = CD3DX12_SHADER_BYTECODE(vertexShader.Get()); psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShader.Get()); psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); psoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); psoDesc.SampleMask = UINT_MAX; psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT; psoDesc.SampleDesc.Count = 1; ThrowIfFailed(m_devices[Primary]->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_pipelineState))); psoDesc.InputLayout = { blurInputElementDescs, _countof(blurInputElementDescs) }; psoDesc.pRootSignature = m_blurRootSignature.Get(); psoDesc.VS = CD3DX12_SHADER_BYTECODE(vertexShaderBlur.Get()); psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShaderBlurU.Get()); psoDesc.DepthStencilState.DepthEnable = false; psoDesc.DSVFormat = DXGI_FORMAT_UNKNOWN; ThrowIfFailed(m_devices[Secondary]->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_blurPipelineStates[0]))); psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShaderBlurV.Get()); ThrowIfFailed(m_devices[Secondary]->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_blurPipelineStates[1]))); } // Create the command lists. ThrowIfFailed(m_devices[Primary]->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_directCommandAllocators[Primary][m_frameIndex].Get(), m_pipelineState.Get(), IID_PPV_ARGS(&m_directCommandLists[Primary]))); ThrowIfFailed(m_devices[Primary]->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, m_copyCommandAllocators[m_frameIndex].Get(), m_pipelineState.Get(), IID_PPV_ARGS(&m_copyCommandList))); ThrowIfFailed(m_copyCommandList->Close()); ThrowIfFailed(m_devices[Secondary]->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_directCommandAllocators[Secondary][m_frameIndex].Get(), m_blurPipelineStates[0].Get(), IID_PPV_ARGS(&m_directCommandLists[Secondary]))); // Note: ComPtr's are CPU objects but these resources need to stay in scope until // the command list that references them has finished executing on the GPU. // We will flush the GPU at the end of this method to ensure the resources are not // prematurely destroyed. ComPtr<ID3D12Resource> vertexBufferUpload; ComPtr<ID3D12Resource> fullscreenQuadVertexBufferUpload; // Create the vertex buffer for the primary adapter. { // Define the geometry for a triangle. Vertex triangleVertices[] = { { { 0.0f, TriangleHalfWidth, TriangleDepth } }, { { TriangleHalfWidth, -TriangleHalfWidth, TriangleDepth } }, { { -TriangleHalfWidth, -TriangleHalfWidth, TriangleDepth } } }; const UINT vertexBufferSize = sizeof(triangleVertices); ThrowIfFailed(m_devices[Primary]->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize), D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&m_vertexBuffer))); ThrowIfFailed(m_devices[Primary]->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vertexBufferUpload))); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the vertex buffer. D3D12_SUBRESOURCE_DATA vertexData = {}; vertexData.pData = reinterpret_cast<UINT8*>(triangleVertices); vertexData.RowPitch = vertexBufferSize; vertexData.SlicePitch = vertexData.RowPitch; UpdateSubresources<1>(m_directCommandLists[Primary].Get(), m_vertexBuffer.Get(), vertexBufferUpload.Get(), 0, 0, 1, &vertexData); m_directCommandLists[Primary]->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_vertexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)); // Initialize the vertex buffer view. m_vertexBufferView.BufferLocation = m_vertexBuffer->GetGPUVirtualAddress(); m_vertexBufferView.StrideInBytes = sizeof(Vertex); m_vertexBufferView.SizeInBytes = sizeof(triangleVertices); } // Create the vertex buffer for the secondary adapter. { // Define the geometry for a fullscreen triangle. VertexPositionUV quadVertices[] = { { { -1.0f, -1.0f, 0.0f, 1.0f }, { 0.0f, 0.0f } }, // Bottom left. { { -1.0f, 1.0f, 0.0f, 1.0f }, { 0.0f, 1.0f } }, // Top left. { { 1.0f, -1.0f, 0.0f, 1.0f }, { 1.0f, 0.0f } }, // Bottom right. { { 1.0f, 1.0f, 0.0f, 1.0f }, { 1.0f, 1.0f } }, // Top right. }; const UINT vertexBufferSize = sizeof(quadVertices); ThrowIfFailed(m_devices[Secondary]->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize), D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&m_fullscreenQuadVertexBuffer))); ThrowIfFailed(m_devices[Secondary]->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fullscreenQuadVertexBufferUpload))); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the vertex buffer. D3D12_SUBRESOURCE_DATA vertexData = {}; vertexData.pData = reinterpret_cast<UINT8*>(quadVertices); vertexData.RowPitch = vertexBufferSize; vertexData.SlicePitch = vertexData.RowPitch; UpdateSubresources<1>(m_directCommandLists[Secondary].Get(), m_fullscreenQuadVertexBuffer.Get(), fullscreenQuadVertexBufferUpload.Get(), 0, 0, 1, &vertexData); m_directCommandLists[Secondary]->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_fullscreenQuadVertexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)); // Initialize the vertex buffer view. m_fullscreenQuadVertexBufferView.BufferLocation = m_fullscreenQuadVertexBuffer->GetGPUVirtualAddress(); m_fullscreenQuadVertexBufferView.StrideInBytes = sizeof(VertexPositionUV); m_fullscreenQuadVertexBufferView.SizeInBytes = sizeof(quadVertices); } // Create the depth stencil view. { D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {}; depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT; depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE; const CD3DX12_CLEAR_VALUE clearValue(DXGI_FORMAT_D32_FLOAT, 1.0f, 0); ThrowIfFailed(m_devices[Primary]->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_D32_FLOAT, m_width, m_height, 1, 0, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), D3D12_RESOURCE_STATE_DEPTH_WRITE, &clearValue, IID_PPV_ARGS(&m_depthStencil) )); m_devices[Primary]->CreateDepthStencilView(m_depthStencil.Get(), &depthStencilDesc, m_dsvHeap->GetCPUDescriptorHandleForHeapStart()); } // Create the constant buffers. { { const UINT64 constantBufferSize = sizeof(ConstantBufferData) * MaxTriangleCount * FrameCount; ThrowIfFailed(m_devices[Primary]->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(constantBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&m_constantBuffer))); // Setup constant buffer data. for (UINT n = 0; n < MaxTriangleCount; n++) { m_constantBufferData[n].velocity = XMFLOAT4(GetRandomFloat(0.01f, 0.02f), 0.0f, 0.0f, 0.0f); m_constantBufferData[n].offset = XMFLOAT4(GetRandomFloat(-5.0f, -1.5f), GetRandomFloat(-1.0f, 1.0f), GetRandomFloat(0.0f, 2.0f), 0.0f); m_constantBufferData[n].color = XMFLOAT4(GetRandomFloat(0.5f, 1.0f), GetRandomFloat(0.5f, 1.0f), GetRandomFloat(0.5f, 1.0f), 1.0f); XMStoreFloat4x4(&m_constantBufferData[n].projection, XMMatrixTranspose(XMMatrixPerspectiveFovLH(XM_PIDIV4, m_aspectRatio, 0.01f, 20.0f))); } // Map the constant buffer. We don't unmap this until the app closes. // Keeping things mapped for the lifetime of the resource is okay. CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU. ThrowIfFailed(m_constantBuffer->Map(0, &readRange, reinterpret_cast<void**>(&m_pCbvDataBegin))); memcpy(m_pCbvDataBegin, &m_constantBufferData[0], constantBufferSize / FrameCount); } { const UINT64 workloadConstantBufferSize = sizeof(WorkloadConstantBufferData) * FrameCount; ThrowIfFailed(m_devices[Primary]->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(workloadConstantBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&m_workloadConstantBuffer))); // Setup constant buffer data. m_workloadConstantBufferData.loopCount = m_psLoopCount; // Map the constant buffer. We don't unmap this until the app closes. // Keeping things mapped for the lifetime of the resource is okay. CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU. ThrowIfFailed(m_workloadConstantBuffer->Map(0, &readRange, reinterpret_cast<void**>(&m_pWorkloadCbvDataBegin))); memcpy(m_pWorkloadCbvDataBegin, &m_workloadConstantBufferData, workloadConstantBufferSize / FrameCount); } { const UINT64 blurWorkloadConstantBufferSize = sizeof(WorkloadConstantBufferData) * FrameCount; ThrowIfFailed(m_devices[Secondary]->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(blurWorkloadConstantBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&m_blurWorkloadConstantBuffer))); // Setup constant buffer data. m_blurWorkloadConstantBufferData.loopCount = m_blurPSLoopCount; // Map the constant buffer. We don't unmap this until the app closes. // Keeping things mapped for the lifetime of the resource is okay. CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU. ThrowIfFailed(m_blurWorkloadConstantBuffer->Map(0, &readRange, reinterpret_cast<void**>(&m_pBlurWorkloadCbvDataBegin))); memcpy(m_pBlurWorkloadCbvDataBegin, &m_blurWorkloadConstantBufferData, blurWorkloadConstantBufferSize / FrameCount); } { ThrowIfFailed(m_devices[Secondary]->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(sizeof(BlurConstantBufferData)), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&m_blurConstantBuffer))); // Map the constant buffer. CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU. ThrowIfFailed(m_blurConstantBuffer->Map(0, &readRange, reinterpret_cast<void**>(&m_pBlurCbvDataBegin))); // Setup constant buffer data. m_pBlurCbvDataBegin[0].offset = 0.5f; m_pBlurCbvDataBegin[0].textureDimensions.x = static_cast<float>(m_width); m_pBlurCbvDataBegin[0].textureDimensions.y = static_cast<float>(m_height); // Unmap the constant buffer because we don't update this again. // If we ever do, it should be buffered by the number of frames like other constant buffers. const CD3DX12_RANGE emptyRange(0, 0); m_blurConstantBuffer->Unmap(0, &emptyRange); m_pBlurCbvDataBegin = nullptr; } } // Close the command lists and execute them to begin the vertex buffer copies into the default heaps. for (UINT i = 0; i < GraphicsAdaptersCount; i++) { ThrowIfFailed(m_directCommandLists[i]->Close()); ID3D12CommandList* ppCommandLists[] = { m_directCommandLists[i].Get() }; m_directCommandQueues[i]->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists); } // Create synchronization objects and wait until assets have been uploaded to the GPU. // We use a cross-adapter fence for handling Signals and Waits between adapters. // We use regular fences for things that don't need to be cross adapter because they don't need the additional overhead associated with being cross-adapter. { // Fence used to control CPU pacing. ThrowIfFailed(m_devices[Secondary]->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_frameFence))); // Fence used by the primary adapter to signal its copy queue that it has completed rendering. // When this is signaled, the primary adapter's copy queue can begin copying to the cross-adapter shared resource. ThrowIfFailed(m_devices[Primary]->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_renderFence))); // Cross-adapter shared fence used by both adapters. // Used by the primary adapter to signal the secondary adapter that it has completed copying to the cross-adapter shared resource. // When this is signaled, the secondary adapter can begin its work. ThrowIfFailed(m_devices[Primary]->CreateFence(0, D3D12_FENCE_FLAG_SHARED | D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER, IID_PPV_ARGS(&m_crossAdapterFences[Primary]))); // For now, require GENERIC_ALL access. HANDLE fenceHandle = nullptr; ThrowIfFailed(m_devices[Primary]->CreateSharedHandle( m_crossAdapterFences[Primary].Get(), nullptr, GENERIC_ALL, nullptr, &fenceHandle)); HRESULT openSharedHandleResult = m_devices[Secondary]->OpenSharedHandle(fenceHandle, IID_PPV_ARGS(&m_crossAdapterFences[Secondary])); // We can close the handle after opening the cross-adapter shared fence. CloseHandle(fenceHandle); ThrowIfFailed(openSharedHandleResult); for (UINT i = 0; i < GraphicsAdaptersCount; i++) { // Create an event handle to use for frame synchronization. m_fenceEvents[i] = CreateEventEx(nullptr, FALSE, FALSE, EVENT_ALL_ACCESS); if (m_fenceEvents == nullptr) { ThrowIfFailed(HRESULT_FROM_WIN32(GetLastError())); } // Wait for the command list to execute; we are reusing the same command // list in our main loop but for now, we just want to wait for setup to // complete before continuing. WaitForGpu(static_cast<GraphicsAdapter>(i)); } } }
void WEHDR::ProcessBloom() { HRESULT hr; UINT width, height; WE::D3D().GetScreen(&width, &height); width /= 8; height /= 8; ID3D11ShaderResourceView* pFromRV = m_pTexBrightPassRV; ID3D11ShaderResourceView* pAuxRV = m_pTexBloomRV[1]; ID3D11RenderTargetView* pAuxRTV = m_pTexBloomRTV[1]; ID3D11RenderTargetView* pToRTV = m_pTexBloomRTV[0]; // Horizontal Blur D3D11_MAPPED_SUBRESOURCE MappedResource; V( m_pImmediateContext->Map( m_pcbBloom, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ); BufferType* pcbBloom = ( BufferType* )MappedResource.pData; XMFLOAT4* avSampleOffsets = pcbBloom->avSampleOffsets; XMFLOAT4* avSampleWeights = pcbBloom->avSampleWeights; float afSampleOffsets[15]; hr = GetSampleOffsets_Bloom_D3D11( width, afSampleOffsets, avSampleWeights, 3.0f, 1.25f ); for (int i = 0; i < 15; i++) { avSampleOffsets[i] = XMFLOAT4( afSampleOffsets[i], 0.0f, 0.0f, 0.0f ); } m_pImmediateContext->Unmap( m_pcbBloom, 0 ); ID3D11Buffer* ppCB[1] = { m_pcbBloom }; m_pImmediateContext->PSSetConstantBuffers( 0, 1, ppCB ); ID3D11RenderTargetView* aRTViews[ 1 ] = { pAuxRTV }; m_pImmediateContext->OMSetRenderTargets( 1, aRTViews, NULL ); ID3D11ShaderResourceView* pViews[1] = {pFromRV}; m_pImmediateContext->PSSetShaderResources( 0, 1, pViews ); ID3D11SamplerState* aSamplers[] = { m_pSamplePoint }; m_pImmediateContext->PSSetSamplers( 0, 1, aSamplers ); m_pImmediateContext->PSSetShader(m_pPSBloom, 0, 0); // Draw quad. m_pImmediateContext->Draw(6, 0); ID3D11ShaderResourceView* pViewsNull[4] = {0,0,0,0}; m_pImmediateContext->PSSetShaderResources( 0, 4, pViewsNull ); // Vertical Blur V( m_pImmediateContext->Map( m_pcbBloom, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ); pcbBloom = ( BufferType* )MappedResource.pData; avSampleOffsets = pcbBloom->avSampleOffsets; avSampleWeights = pcbBloom->avSampleWeights; hr = GetSampleOffsets_Bloom_D3D11( height, afSampleOffsets, avSampleWeights, 3.0f, 1.25f ); for (int i = 0; i < 15; i++) { avSampleOffsets[i] = XMFLOAT4( 0.0f, afSampleOffsets[i], 0.0f, 0.0f ); } m_pImmediateContext->Unmap( m_pcbBloom, 0 ); ppCB[0] = m_pcbBloom; m_pImmediateContext->PSSetConstantBuffers( 0, 1, ppCB ); aRTViews[ 0 ] = pToRTV; m_pImmediateContext->OMSetRenderTargets( 1, aRTViews, NULL ); pViews[0] = pAuxRV; m_pImmediateContext->PSSetShaderResources( 0, 1, pViews ); m_pImmediateContext->PSSetShader(m_pPSBloom, 0, 0); // Draw quad. m_pImmediateContext->Draw(6, 0); m_pImmediateContext->PSSetShaderResources( 0, 4, pViewsNull ); ID3D11Buffer* ppCBNull[1] = { NULL }; m_pImmediateContext->PSSetConstantBuffers( 0, 1, ppCBNull ); }
void CubeDemo::Initialize() { SetCurrentDirectory(Utility::ExecutableDirectory().c_str()); // Compile the shader UINT shaderFlags = 0; #if defined( DEBUG ) || defined( _DEBUG ) shaderFlags |= D3DCOMPILE_DEBUG; shaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; #endif ID3D10Blob* compiledShader = nullptr; ID3D10Blob* errorMessages = nullptr; HRESULT hr = D3DCompileFromFile(L"C:\\Users\\Nick\\Source\\Repos\\DirectXTest\\source\\Library\\Content\\BasicEffect.fx", nullptr, nullptr, nullptr, "fx_5_0", shaderFlags, 0, &compiledShader, &errorMessages); if (FAILED(hr)) { char* errorMessage = (errorMessages != nullptr ? (char*)errorMessages->GetBufferPointer() : "D3DX11CompileFromFile() failed"); GameException ex(errorMessage, hr); ReleaseObject(errorMessages); throw ex; } // Create an effect object from the compiled shader hr = D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), 0, mGame->Direct3DDevice(), &mEffect); if (FAILED(hr)) { throw GameException("D3DX11CreateEffectFromMemory() failed.", hr); } ReleaseObject(compiledShader); // Look up the technique, pass, and WVP variable from the effect mTechnique = mEffect->GetTechniqueByName("main11"); if (mTechnique == nullptr) { throw GameException("ID3DX11Effect::GetTechniqueByName() could not find the specified technique.", hr); } mPass = mTechnique->GetPassByName("p0"); if (mPass == nullptr) { throw GameException("ID3DX11EffectTechnique::GetPassByName() could not find the specified pass.", hr); } ID3DX11EffectVariable* variable = mEffect->GetVariableByName("WorldViewProjection"); if (variable == nullptr) { throw GameException("ID3DX11Effect::GetVariableByName() could not find the specified variable.", hr); } mWvpVariable = variable->AsMatrix(); if (mWvpVariable->IsValid() == false) { throw GameException("Invalid effect variable cast."); } // Create the input layout D3DX11_PASS_DESC passDesc; mPass->GetDesc(&passDesc); D3D11_INPUT_ELEMENT_DESC inputElementDescriptions[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; if (FAILED(hr = mGame->Direct3DDevice()->CreateInputLayout(inputElementDescriptions, ARRAYSIZE(inputElementDescriptions), passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &mInputLayout))) { throw GameException("ID3D11Device::CreateInputLayout() failed.", hr); } // Create the vertex and index buffers BasicEffectVertex vertices[] = { BasicEffectVertex(XMFLOAT4(-1.0f, +1.0f, -1.0f, 1.0f), XMFLOAT4(reinterpret_cast<const float*>(&ColorHelper::Green))), BasicEffectVertex(XMFLOAT4(+1.0f, +1.0f, -1.0f, 1.0f), XMFLOAT4(reinterpret_cast<const float*>(&ColorHelper::Yellow))), BasicEffectVertex(XMFLOAT4(+1.0f, +1.0f, +1.0f, 1.0f), XMFLOAT4(reinterpret_cast<const float*>(&ColorHelper::White))), BasicEffectVertex(XMFLOAT4(-1.0f, +1.0f, +1.0f, 1.0f), XMFLOAT4(reinterpret_cast<const float*>(&ColorHelper::BlueGreen))), BasicEffectVertex(XMFLOAT4(-1.0f, -1.0f, +1.0f, 1.0f), XMFLOAT4(reinterpret_cast<const float*>(&ColorHelper::Blue))), BasicEffectVertex(XMFLOAT4(+1.0f, -1.0f, +1.0f, 1.0f), XMFLOAT4(reinterpret_cast<const float*>(&ColorHelper::Purple))), BasicEffectVertex(XMFLOAT4(+1.0f, -1.0f, -1.0f, 1.0f), XMFLOAT4(reinterpret_cast<const float*>(&ColorHelper::Red))), BasicEffectVertex(XMFLOAT4(-1.0f, -1.0f, -1.0f, 1.0f), XMFLOAT4(reinterpret_cast<const float*>(&ColorHelper::Black))) }; D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.ByteWidth = sizeof(BasicEffectVertex) * ARRAYSIZE(vertices); vertexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA vertexSubResourceData; ZeroMemory(&vertexSubResourceData, sizeof(vertexSubResourceData)); vertexSubResourceData.pSysMem = vertices; if (FAILED(mGame->Direct3DDevice()->CreateBuffer(&vertexBufferDesc, &vertexSubResourceData, &mVertexBuffer))) { throw GameException("ID3D11Device::CreateBuffer() failed."); } UINT indices[] = { 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 3, 2, 5, 3, 5, 4, 2, 1, 6, 2, 6, 5, 1, 7, 6, 1, 0, 7, 0, 3, 4, 0, 4, 7 }; D3D11_BUFFER_DESC indexBufferDesc; ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc)); indexBufferDesc.ByteWidth = sizeof(UINT) * ARRAYSIZE(indices); indexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; D3D11_SUBRESOURCE_DATA indexSubResourceData; ZeroMemory(&indexSubResourceData, sizeof(indexSubResourceData)); indexSubResourceData.pSysMem = indices; if (FAILED(mGame->Direct3DDevice()->CreateBuffer(&indexBufferDesc, &indexSubResourceData, &mIndexBuffer))) { throw GameException("ID3D11Device::CreateBuffer() failed."); } }
bool init(HINSTANCE hInstance, int nCmdShow) { //Open console window AllocConsole(); freopen("conin$", "r", stdin); freopen("conout$", "w", stdout); freopen("conout$", "w", stderr); srand(time(NULL)); //add some spheres for (int i = 0; i < 2500; i++) { float radius = (rand() % 150 + 100) / 100.0f; Sphere sphere(XMFLOAT3((rand() % 500 - 250) / 10.0f, (rand() % 250 + 250) / 10.0f, (rand() % 500 - 250) / 10.0f), XMFLOAT4((rand() % 100) / 100.0f, (rand() % 100) / 100.0f, (rand() % 100) / 100.0f, 1.0f), radius, radius * 200.0f); Spheres.push_back(sphere); } //window class WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = "WindowClass1"; wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_APPLICATION); if (!RegisterClassEx(&wcex)) return E_FAIL; //create window g_hInst = hInstance; RECT rc = { 0, 0, 1280, 800 }; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); g_hWnd = CreateWindow("WindowClass1", "Simple Sphere Physics", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance, NULL); if (!g_hWnd) return E_FAIL; ShowWindow(g_hWnd, nCmdShow); return initDirectx(); }
void update() { // Update our time static float t = 0.0f; static DWORD dwTimeStart = 0; DWORD dwTimeCur = GetTickCount(); if (dwTimeStart == 0) dwTimeStart = dwTimeCur; t = (dwTimeCur - dwTimeStart) / 1000.0f; dt = t - prev_time; prev_time = t; //gets cursor movement to update camera POINT currCursorPos; GetCursorPos(&currCursorPos); SetCursorPos(500, 500); g_Theta += (currCursorPos.x - 500) * 3.14159 / 180 / 10; g_Phi -= (currCursorPos.y - 500) * 3.14159 / 180 / 10; //this is for a panning camera //g_Theta = t / 3; //g_Phi = XM_PIDIV4 / 3; //add spheres if the spacebar key is pressed if (GetAsyncKeyState(VK_SPACE)) { float radius = (rand() % 150 + 100) / 100.0f; Sphere sphere(XMFLOAT3((rand() % 500 - 250) / 10.0f, (rand() % 250 + 250) / 10.0f, (rand() % 500 - 250) / 10.0f), XMFLOAT4((rand() % 100) / 100.0f, (rand() % 100) / 100.0f, (rand() % 100) / 100.0f, 1.0f), radius, radius * 200.0f); Spheres.push_back(sphere); } //multithread the simulation std::thread thread1(handle_collisions, 0, Spheres.size() / 4); std::thread thread2(handle_collisions, Spheres.size() / 4, Spheres.size() / 2); std::thread thread3(handle_collisions, Spheres.size() / 2, 3 * Spheres.size() / 4); std::thread thread4(handle_collisions, 3 * Spheres.size() / 4, Spheres.size()); thread1.join(); thread2.join(); thread3.join(); thread4.join(); //apply bounds for the spheres for (int i = 0; i < Spheres.size(); i++) { Spheres[i].ApplyForce(XMFLOAT3(0.0f, -9.8f * Spheres[i].Mass, 0.0f), dt); if (Spheres[i].Position.y - Spheres[i].Radius < 0) { Spheres[i].Position.y = Spheres[i].Radius; Spheres[i].Velocity.y *= -0.5f; } if (Spheres[i].Position.x - Spheres[i].Radius < -50.0f) { Spheres[i].Position.x = -50.0f + Spheres[i].Radius; Spheres[i].Velocity.x *= -0.5f; } else if (Spheres[i].Position.x + Spheres[i].Radius > 50.0f) { Spheres[i].Position.x = 50.0f - Spheres[i].Radius; Spheres[i].Velocity.x *= -0.5f; } if (Spheres[i].Position.z - Spheres[i].Radius < -50.0f) { Spheres[i].Position.z = -50.0f + Spheres[i].Radius; Spheres[i].Velocity.z *= -0.5f; } else if (Spheres[i].Position.z + Spheres[i].Radius > 50.0f) { Spheres[i].Position.z = 50.0f - Spheres[i].Radius; Spheres[i].Velocity.z *= -0.5f; } Spheres[i].Update(dt); } //makes the interface a little cleaner by restricting camera angles if (g_Phi > 3.14159 / 2) { g_Phi = 3.14159 / 2; } if (g_Phi < -3.14159 / 2) { g_Phi = -3.14159 / 2; } }
InstancingAndCullingApp::InstancingAndCullingApp(HINSTANCE hInstance) : D3DApp(hInstance), mSkullVB(0), mSkullIB(0), mSkullIndexCount(0), mInstancedBuffer(0), mVisibleObjectCount(0), mFrustumCullingEnabled(true) { mMainWndCaption = L"Instancing and Culling Demo"; srand((unsigned int)time((time_t *)NULL)); mLastMousePos.x = 0; mLastMousePos.y = 0; mCam.SetPosition(0.0f, 2.0f, -15.0f); XMMATRIX I = XMMatrixIdentity(); XMMATRIX skullScale = XMMatrixScaling(0.5f, 0.5f, 0.5f); XMMATRIX skullOffset = XMMatrixTranslation(0.0f, 1.0f, 0.0f); XMStoreFloat4x4(&mSkullWorld, XMMatrixMultiply(skullScale, skullOffset)); 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); 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); 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); mSkullMat.Ambient = XMFLOAT4(0.4f, 0.4f, 0.4f, 1.0f); mSkullMat.Diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f); mSkullMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f); }
void EnemyIceBear::Initialize(const GameContext& gameContext) { UNREFERENCED_PARAMETER(gameContext); m_CurrentHealth = 100.0f; // ADD MODEL auto physX = PhysxManager::GetInstance()->GetPhysics(); m_pIceBearModel = new GameObject(); auto iceBearModelComponent = new ModelComponent(L"./Resources/Meshes/IceBear.ovm"); iceBearModelComponent->SetMaterial(3); m_pIceBearModel->AddComponent(iceBearModelComponent); auto rigidbody = new RigidBodyComponent(); rigidbody->SetKinematic(true); m_pIceBearModel->AddComponent(rigidbody); auto defaultMaterial = physX->createMaterial(0.5f, 0.5f, 0.1f); auto iceBearMesh = ContentManager::Load<PxConvexMesh>(L"./Resources/Meshes/IceBear.ovpc"); shared_ptr<PxGeometry> bearGeo(new PxConvexMeshGeometry(iceBearMesh)); auto IceBearCollider = new ColliderComponent(bearGeo, *defaultMaterial); m_pIceBearModel->AddComponent(IceBearCollider); AddChild(m_pIceBearModel); m_pIceBearModel->GetTransform()->Translate(m_Position); m_pHealthBarInside = new GameObject(); m_pHealthBarInside->AddComponent(new SpriteComponent(L"./Resources/Textures/IceBear_healthbar_green.png", XMFLOAT2(0.f, 0.5f), XMFLOAT4(1, 1, 1, 1.0f))); AddChild(m_pHealthBarInside); m_pHealthBarFrame = new GameObject(); m_pHealthBarFrame->AddComponent(new SpriteComponent(L"./Resources/Textures/IceBear_healthbar_empty.png", XMFLOAT2(0.5f, 0.5f), XMFLOAT4(1, 1, 1, 1.0f))); AddChild(m_pHealthBarFrame); }
void CMainMenu::Render(void) { //m_pR->PreRender(); //Draw the Menu and stuff m_pR->Render2D(m_pMenuBG, XMFLOAT4(0.0f, 0.0f, 1280.0f, 768.0f), XMFLOAT4(0.0f, 0.0f, 1920.0f, 1080.0f)); string main = "Main Menu"; m_pFont->WriteText(XMFLOAT2(200.0f, 100.0f), 1.0f, main, XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)); main = "Join Game"; if(m_eCurrS == msJoin) { m_pFont->WriteText(XMFLOAT2(240.0f, 150.0f), 1.0f, main, XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)); } else { m_pFont->WriteText(XMFLOAT2(220.0f, 150.0f), 1.0f, main, XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)); } main = "Credits"; if(m_eCurrS == msCredit) { m_pFont->WriteText(XMFLOAT2(240.0f, 175.0f), 1.0f, main, XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)); } else { m_pFont->WriteText(XMFLOAT2(220.0f, 175.0f), 1.0f, main, XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)); } main = "TestArea"; if(m_eCurrS == msTest) { m_pFont->WriteText(XMFLOAT2(240.0f, 200.0f), 1.0f, main, XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)); } else { m_pFont->WriteText(XMFLOAT2(220.0f, 200.0f), 1.0f, main, XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)); } main = "Exit"; if(m_eCurrS == msExit) { m_pFont->WriteText(XMFLOAT2(240.0f, 225.0f), 1.0f, main, XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)); } else { m_pFont->WriteText(XMFLOAT2(220.0f, 225.0f), 1.0f, main, XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)); } //m_pR->PostRender(); }
void wiBULLET::addTriangleMesh(const vector<SkinnedVertex>& vertices, const vector<unsigned int>& indices, const XMFLOAT3& sca, const XMFLOAT4& rot, const XMFLOAT3& pos , float newMass, float newFriction, float newRestitution, float newDamping, bool kinematic){ int totalVerts = vertices.size(); int totalTriangles = indices.size() / 3; btVector3* btVerts = new btVector3[totalVerts]; for (unsigned int i = 0; i<vertices.size(); ++i) btVerts[i] = (btVector3(vertices[i].pos.x,vertices[i].pos.y,vertices[i].pos.z)); int* btInd = new int[indices.size()]; for (unsigned int i = 0; i<indices.size(); ++i) btInd[i] = indices[i]; int vertStride = sizeof(btVector3); int indexStride = 3*sizeof(int); btTriangleIndexVertexArray* indexVertexArrays = new btTriangleIndexVertexArray( totalTriangles, btInd, indexStride, totalVerts, (btScalar*) &btVerts[0].x(), vertStride ); bool useQuantizedAabbCompression = true; btCollisionShape* shape = new btBvhTriangleMeshShape(indexVertexArrays,useQuantizedAabbCompression); shape->setMargin(btScalar(0.05)); shape->setLocalScaling(btVector3(sca.x,sca.y,sca.z)); collisionShapes.push_back(shape); btTransform shapeTransform; shapeTransform.setIdentity(); shapeTransform.setOrigin(btVector3(pos.x,pos.y,pos.z)); shapeTransform.setRotation(btQuaternion(rot.x,rot.y,rot.z,rot.w)); { btScalar mass(newMass); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f && !kinematic); btVector3 localInertia(0,0,0); if (isDynamic) shape->calculateLocalInertia(mass,localInertia); else mass=0; //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(shapeTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,shape,localInertia); rbInfo.m_friction=newFriction; rbInfo.m_restitution=newRestitution; rbInfo.m_linearDamping = newDamping; rbInfo.m_angularDamping = newDamping; btRigidBody* body = new btRigidBody(rbInfo); if(kinematic) body->setCollisionFlags( body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); body->setActivationState( DISABLE_DEACTIVATION ); //add the body to the dynamics world dynamicsWorld->addRigidBody(body); if (body && body->getMotionState()) { btTransform trans; body->getMotionState()->getWorldTransform(trans); btQuaternion nRot = trans.getRotation(); btVector3 nPos = trans.getOrigin(); transforms.push_back(new PhysicsTransform( XMFLOAT4(nRot.getX(),nRot.getY(),nRot.getZ(),nRot.getW()),XMFLOAT3(nPos.getX(),nPos.getY(),nPos.getZ())) ); } } }
bool Graphics::Initialize(int a_nScreenWidth, int a_nScreenHeight, HWND a_hWindow) { bool result; m_pD3DCore = new D3DCore(); if(!m_pD3DCore) { return false; } result = m_pD3DCore->Initialize( a_nScreenWidth, a_nScreenHeight, VSYNC_ENABLED, a_hWindow, FULL_SCREEN, NEAR_PLANE, FAR_PLANE); if(!result) { MessageBoxA(a_hWindow, "Failed to initialize D3D.", "Error", MB_OK); return false; } m_pCamera = new Camera(); if(!m_pCamera) { return false; } m_pCamera->SetPosition(XMFLOAT3(0.0f, 0.0f, 500.0f)); m_pTriangleModel = new TriangleModel(); if(!m_pTriangleModel) { return false; } result = m_pTriangleModel->Initialize(m_pD3DCore->GetDevice()); if(!result) { MessageBoxA(a_hWindow, "Failed to initialize Model.", "Error", MB_OK); return false; } m_pSkyBoxModel = new CubeModel(); if(!m_pSkyBoxModel) { return false; } result = m_pSkyBoxModel->Initialize(m_pD3DCore->GetDevice()); if(!result) { return false; } m_pAssimpModel = new AssimpModel(); if(!m_pAssimpModel) { return false; } result = m_pAssimpModel->Initialize(m_pD3DCore->GetDevice()); if(!result) { MessageBoxA(a_hWindow, "Failed to initialize Model.", "Error", MB_OK); return false; } m_pSkyBoxMaterial = new SkyBox(); if(!m_pSkyBoxMaterial) { return false; } m_pTriangleMaterial = new AmbientLighting(); if(!m_pTriangleMaterial) { return false; } m_pAssimpMaterial = new ModelMaterial(); if(!m_pAssimpMaterial) { return false; } m_pSceneSettings = new SceneSettings(); if(!m_pSceneSettings) { return false; } m_pSceneSettings->DefaultColor = XMFLOAT4(0.1f, 0.1f, 0.4f, 1.0f); m_pSceneSettings->BackgroundColor = XMFLOAT4(0.7f, 0.5f, 0.2f, 1.0f); m_pSceneSettings->AmbientIntensity = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); result = m_pSkyBoxMaterial->Initialize(m_pD3DCore->GetDevice(), m_pSceneSettings); if(!result) { MessageBoxA(a_hWindow, "Failed to initialize Material.", "Error", MB_OK); return false; } result = m_pTriangleMaterial->Initialize(m_pD3DCore->GetDevice(), m_pSceneSettings); if(!result) { return false; } result = m_pAssimpMaterial->Initialize(m_pD3DCore->GetDevice(), m_pSceneSettings); if(!result) { return false; } D3D11_RASTERIZER_DESC rd; // Create wireframe/no cull mode for debug ZeroMemory(&rd, sizeof(D3D11_RASTERIZER_DESC)); rd.FillMode = D3D11_FILL_WIREFRAME; rd.CullMode = D3D11_CULL_NONE; rd.FrontCounterClockwise = false; rd.DepthClipEnable = true; m_pD3DCore->GetDevice()->CreateRasterizerState(&rd, &m_pRSWireFrame); return true; }
void CubeDemo::initialize() { SetCurrentDirectory(Utility::ExecutableDirectory().c_str()); UINT shaderFlags = 0; #if defined(DEBUG) || defined(_DEBUG) shaderFlags |= D3DCOMPILE_DEBUG; shaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; #endif ID3D10Blob * compiledShader = nullptr; ID3D10Blob * errorMessages = nullptr; HRESULT hr = D3DCompileFromFile(L"Content\\Effects\\BasicEffect.fx", nullptr, nullptr, nullptr, "fx_5_0", shaderFlags, 0, &compiledShader, &errorMessages); //if (errorMessages != nullptr) //{ // char * message = (char*)errorMessages->GetBufferPointer(); // GameException ex((wchar_t*)errorMessages->GetBufferPointer(), hr); // ReleaseObject(errorMessages); // throw ex; // //ReleaseObject(compiledShader); //} if (FAILED(hr)) { throw GameException(L"D3DX11CompileFromFile() failed.", hr); } hr = D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), 0, mGame->device(), &mEffect); if (FAILED(hr)) { throw GameException(L"D3DX11CreateEffectFromMemory() failed", hr); } ReleaseObject(compiledShader); mTechnique = mEffect->GetTechniqueByName("main11"); if (mTechnique == nullptr) { throw GameException(L"ID3D11Effect::GetTechniqueByName() unable to find techique main11.", hr); } mPass = mTechnique->GetPassByName("p0"); if (mPass == nullptr) { throw GameException(L"ID3D11EffectTechnique::GetPassByName() unable to find pass p0", hr); } ID3DX11EffectVariable * variable = mEffect->GetVariableByName("WorldViewProjection"); if (variable == nullptr) { throw GameException(L"ID3DX11Effect::GetVariableByName() unable to find variable WorldViewProjection"); } mWvpVariable = variable->AsMatrix(); if (!mWvpVariable->IsValid()) { throw GameException(L"Invaild effect variable cast"); } D3DX11_PASS_DESC passDesc; mPass->GetDesc(&passDesc); D3D11_INPUT_ELEMENT_DESC inputElementDescriptions[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (FAILED(hr = mGame->device()->CreateInputLayout(inputElementDescriptions, ARRAYSIZE(inputElementDescriptions), passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &mInputLayout))) { throw GameException(L"ID3D11Device::CreateInputLayout() failed", hr); } BasicEffectVertex vertices[] = { BasicEffectVertex(XMFLOAT4(-1.0f, 1.0f, -1.0f, 1.0f), XMFLOAT4(reinterpret_cast<float*>(&Colors::RED))), BasicEffectVertex(XMFLOAT4(1.0f, 1.0f, -1.0f, 1.0f), XMFLOAT4(reinterpret_cast<float*>(&Colors::GREEN))), BasicEffectVertex(XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT4(reinterpret_cast<float*>(&Colors::BLACK))) , BasicEffectVertex(XMFLOAT4(-1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT4(reinterpret_cast<float*>(&Colors::WHITE))), BasicEffectVertex(XMFLOAT4(-1.0f,- 1.0f, 1.0f, 1.0f), XMFLOAT4(reinterpret_cast<float*>(&Colors::YELLOW))), BasicEffectVertex(XMFLOAT4(+1.0f, -1.0f, +1.0f, 1.0f), XMFLOAT4(reinterpret_cast<float*>(&Colors::BLACK))), BasicEffectVertex(XMFLOAT4(1.0f, -1.0f, -1.0f, 1.0f), XMFLOAT4(reinterpret_cast<float*>(&Colors::CYAN))), BasicEffectVertex(XMFLOAT4(-1.0f, -1.0f, -1.0f, 1.0f), XMFLOAT4(reinterpret_cast<float*>(&Colors::GREEN))) }; D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.ByteWidth = sizeof(BasicEffectVertex)* ARRAYSIZE(vertices); vertexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA vertexSubResourceData; ZeroMemory(&vertexSubResourceData, sizeof(vertexSubResourceData)); vertexSubResourceData.pSysMem = vertices; if (FAILED(mGame->device()->CreateBuffer(&vertexBufferDesc, &vertexSubResourceData, &mVertexBuffer))) { throw GameException(L"ID3D11Device::CreateBuffer() failed"); } UINT indices[] = { 0,1,2, 0,2,3, 4,5,6, 4,6,7, 3,2,5, 3,5,4, 2,1,6, 2,6,5, 1,7,6, 1,0,7, 0,3,4, 0,4,7, }; D3D11_BUFFER_DESC indexBufferDesc; ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc)); indexBufferDesc.ByteWidth = sizeof(indices); indexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; D3D11_SUBRESOURCE_DATA indexSubResourceData; ZeroMemory(&indexSubResourceData, sizeof(indexSubResourceData)); indexSubResourceData.pSysMem = indices; if (FAILED(mGame->device()->CreateBuffer(&indexBufferDesc, &indexSubResourceData, &mIndexBuffer))) { throw GameException(L"ID3D11Device::CreateBuffer() failed"); } mCamera->setPosition(0.0f, 0.0f, 5.0f); }
void StandardRenderer::render(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, GameObject* gameObject) { // simplest possible renderer // get world matrix XMMATRIX worldMatrix = gameObject->transformMatrix; // only supports one parent at moment if (gameObject->parent) { // for some reason it breaks if you remove this line... // it could be something to do with the warning C4316 XMMATRIX parentTransform = gameObject->parent->transformMatrix; worldMatrix *= parentTransform; } GameContext * gameContext = gameObject->gameContext; XMMATRIX viewMatrix = gameContext->renderingContext->primaryCamera->viewMatrix; XMMATRIX projectionMatrix = gameContext->renderingContext->projectionMatrix; XMMATRIX matWorldViewProjection = worldMatrix * viewMatrix * projectionMatrix; // update constant buffers gameObject->shaderPair->updateBuffersPerObject(pd3dImmediateContext, worldMatrix, matWorldViewProjection, XMFLOAT4(1, 1, 1, 1)); setMesh(pd3dImmediateContext, gameObject->sharedMesh); renderMesh(pd3dImmediateContext, gameObject->sharedMesh); }
void DiffuseLight::setAmbientColor(float red, float green, float blue, float alpha) { ambientColor = XMFLOAT4(red, green, blue, alpha); }
bool LightManager::Initialize(ID3D11Device* _device, int _currentLevel) { HRESULT result; int count; #pragma region Pointlight level positioning // Level 1 XMFLOAT4 hus01_lightPos[] = { XMFLOAT4(15.0f, 30.0f, -11.0f, 1.0f), XMFLOAT4(-46.0f, 28.0f, 8.0f, 1.0f), XMFLOAT4(-20.0f, 31.0f, -3.0f, 1.0f), XMFLOAT4(37.0f, 11.0f, 9.0f, 1.0f), XMFLOAT4(0.0f, 5.0f, -5.0f, 1.0f) }; // Level 2 XMFLOAT4 hus02_lightPos[] = { XMFLOAT4(-1.0f, 46.0f, 7.5f, 1.0f), XMFLOAT4(-1.3f, 26.0f, 65.0f, 1.0f), XMFLOAT4(-3.70f, 65.20f, 70.5f, 1.0f), XMFLOAT4(-113.8f, 26.7f, 81.5f, 1.0f), XMFLOAT4(-121.3f, 64.7f, 61.0f, 1.0f), XMFLOAT4(-117.8f, 51.7f, 37.2f, 1.0f), XMFLOAT4(-111.8f, 50.7f, -12.5f, 1.0f), XMFLOAT4(-175.8f, 57.7f, -10.5f, 1.0f), XMFLOAT4(-227.8f, 69.7f, 77.5f, 1.0f), XMFLOAT4(-233.8f, 73.7f, 36.5f, 1.0f), XMFLOAT4(-266.4f, 56.7f, 23.5f, 1.0f), XMFLOAT4(-266.4f, 64.7f, 68.5f, 1.0f), // End of crystal lights XMFLOAT4(0.0f, 0.0f, 35.0f, 1.0f), XMFLOAT4(0.0f, 19.0f, 31.0f, 1.0f), // Start of scene lights XMFLOAT4(0.0f, 19.0f, 3.0f, 1.0f), XMFLOAT4(0.0f, 38.0f, 44.0f, 1.0f), XMFLOAT4(-11.8f, 60.1f, 32.7f, 1.0f), XMFLOAT4(85.4f, 72.9f, 8.5f, 1.0f), XMFLOAT4(-74.7f, 38.2f, 33.0f, 1.0f), XMFLOAT4(-176.6f, 46.0f, 33.0f, 1.0f), XMFLOAT4(-200.0f, 68.3f, 68.1f, 1.0f) }; // Level 3 XMFLOAT4 hus03_lightPos[] = { XMFLOAT4(50.1f, 28.2f, -22.6f, 1.0f), XMFLOAT4(26.9f, 27.6f, 29.6f, 1.0f), XMFLOAT4(59.5f, 30.7f, 33.0f, 1.0f), XMFLOAT4(62.3f, 31.9f, 88.6f, 1.0f), XMFLOAT4(62.6f, 29.6f, 173.3f, 1.0f), XMFLOAT4(-14.5f, 5.2f, 166.2f, 1.0f), XMFLOAT4(-37.4f, 21.8f, 190.2f, 1.0f), XMFLOAT4(-66.2f, 35.7f, 166.0f, 1.0f), XMFLOAT4(-104.2f, 46.6f, 239.0f, 1.0f), XMFLOAT4(-104.3f, 45.5f, 295.6f, 1.0f), XMFLOAT4(-75.5f, 45.6f, 296.7f, 1.0f), XMFLOAT4(-18.1f, 43.0f, 358.0f, 1.0f), XMFLOAT4(-71.0f, 25.3f, 389.8f, 1.0f), XMFLOAT4(-71.0f, 25.3f, 448.8f, 1.0f), XMFLOAT4(-71.0f, 25.3f, 496.5f, 1.0f), XMFLOAT4(-18.0f, 44.4f, 478.9f, 1.0f), XMFLOAT4(-18.0f, 44.4f, 417.6f, 1.0f), // End of crystal lights XMFLOAT4(0.0f, 21.4f, 15.3f, 1.0f), XMFLOAT4(58.1f, 21.4f, -7.2f, 1.0f), XMFLOAT4(58.1f, 28.4f, 60.9f, 1.0f), // Start of scene lights XMFLOAT4(58.1f, 28.4f, 136.7f, 1.0f), XMFLOAT4(45.7f, 28.4f, 195.8f, 1.0f), XMFLOAT4(0.5f, 52.7f, 171.9f, 1.0f), XMFLOAT4(-49.8f, 7.8f, 177.7f, 1.0f), XMFLOAT4(-106.0f, 29.8f, 180.7f, 1.0f), XMFLOAT4(-106.0f, 29.8f, 257.0f, 1.0f), XMFLOAT4(-103.7f, 29.8f, 298.2f, 1.0f), XMFLOAT4(-42.3f, 29.8f, 298.2f, 1.0f), XMFLOAT4(-33.0f, 29.8f, 359.1f, 1.0f), XMFLOAT4(-33.3f, 29.8f, 416.4f, 1.0f), XMFLOAT4(-42.9f, 29.8f, 499.1f, 1.0f), XMFLOAT4(-42.9f, 29.8f, 499.1f, 1.0f) }; #pragma endregion // Directional light enviroLightObj.light.direction = { 0.0f, 1.0f, 2.0f }; enviroLightObj.light.diffuse = { 0.0f, 0.0f, 0.0f, 1.0f }; enviroLightObj.light.ambient = { 0.2f, 0.2f, 0.2f, 1.0f }; XMFLOAT4 crystalDiff = { 0.2f, 0.4f, 1.0f, 1.0f }; lightBufferObj.lights = new PointLight[LIGHT_COUNT]; if (!lightBufferObj.lights) { return false; } for (int i = 0; i < LIGHT_COUNT; i++) { lightBufferObj.lights[i] = PointLight(); } // Point lights switch (_currentLevel) { case 0: count = 5; for (int i = 0; i < count; i++) { lightBufferObj.lights[i].position = hus01_lightPos[i]; lightBufferObj.lights[i].diffuse = crystalDiff; lightBufferObj.lights[i].intensity = 10; lightBufferObj.lights[i].attenuation = { 0.0f, 0.0f, 0.6f }; } lightBufferObj.lights[4].diffuse = { 0.8f, 0.8f, 0.8f, 1.0f }; lightBufferObj.lights[4].attenuation = { 0.0f, 0.2f, 0.0f }; lightBufferObj.lights[4].intensity = 5; break; case 1: count = 21; // Crystal lights for (int i = 0; i < count - 8; i++) { lightBufferObj.lights[i].position = hus02_lightPos[i]; lightBufferObj.lights[i].diffuse = crystalDiff; lightBufferObj.lights[i].intensity = 10; lightBufferObj.lights[i].attenuation = { 0.0f, 0.0f, 0.6f }; } // Enviroment lights for (int i = 12; i < count; i++) { lightBufferObj.lights[i].position = hus02_lightPos[i]; lightBufferObj.lights[i].diffuse = { 0.7f, 0.5f, 0.5f, 1.0f }; lightBufferObj.lights[i].intensity = 3; lightBufferObj.lights[i].attenuation = { 0.0f, 0.5f, 0.0f }; } break; case 2: count = 32; // Crystal lights for (int i = 0; i < count - 15; i++) { lightBufferObj.lights[i].position = hus03_lightPos[i]; lightBufferObj.lights[i].diffuse = crystalDiff; lightBufferObj.lights[i].intensity = 10; lightBufferObj.lights[i].attenuation = { 0.0f, 0.0f, 0.6f }; } // Enviroment lights for (int i = 15; i < count; i++) { lightBufferObj.lights[i].position = hus03_lightPos[i]; lightBufferObj.lights[i].diffuse = { 0.6f, 0.6f, 0.8f, 1.0f }; lightBufferObj.lights[i].intensity = 5; lightBufferObj.lights[i].attenuation = { 0.0f, 0.5f, 0.0f }; } break; } lightBuffer = new ID3D11Buffer*[2]; D3D11_BUFFER_DESC lightBufferDesc; ZeroMemory(&lightBufferDesc, sizeof(D3D11_BUFFER_DESC)); lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; lightBufferDesc.Usage = D3D11_USAGE_DEFAULT; lightBufferDesc.ByteWidth = sizeof(DirectionalLight); result = _device->CreateBuffer(&lightBufferDesc, NULL, &lightBuffer[0]); if (FAILED(result)) { return false; } lightBufferDesc.ByteWidth = sizeof(PointLight) * LIGHT_COUNT; result = _device->CreateBuffer(&lightBufferDesc, NULL, &lightBuffer[1]); if (FAILED(result)) { return false; } return true; }
GameState Menu::Update(const float dt) { guiMan->Update(dt); if(guiMan->_guiElements["SINGLEPLAYER"]->Clicked()) return GameState::Playing; if(guiMan->_guiElements["MULTIPLAYER"]->Clicked()) return GameState::GameLobby; if(guiMan->_guiElements["EXIT"]->Clicked()) PostQuitMessage(0); if(guiMan->_guiElements["SINGLEPLAYER"]->IsMouseHovering() || menuOptions == MENU_OPTIONS::SINGLEPLAYER) { guiMan->_guiElements["SINGLEPLAYER"]->SetColor(XMFLOAT4(1, 1, 1, 1)); guiMan->_guiElements["SINGLEPLAYER"]->SetScale(XMFLOAT2(1.105f, 1.105f)); menuOptions = MENU_OPTIONS::SINGLEPLAYER; GUITexture* tex = (GUITexture*)(guiMan->_guiElements["Texture"]); RECT* rectBig = GetRECTFromRect(guiMan->_guiElements["SINGLEPLAYER"]->GetRect()); tex->SetRect(rectBig); delete rectBig; } else { guiMan->_guiElements["SINGLEPLAYER"]->SetColor(XMFLOAT4(0, 0, 0, 1)); guiMan->_guiElements["SINGLEPLAYER"]->SetScale(XMFLOAT2(1, 1)); } if(guiMan->_guiElements["MULTIPLAYER"]->IsMouseHovering() || menuOptions == MENU_OPTIONS::MULTIPLAYER) { guiMan->_guiElements["MULTIPLAYER"]->SetColor(XMFLOAT4(1, 0, 0, 1)); guiMan->_guiElements["MULTIPLAYER"]->SetScale(XMFLOAT2(1, 1)); menuOptions = MENU_OPTIONS::MULTIPLAYER; GUITexture* tex = (GUITexture*)(guiMan->_guiElements["Texture"]); RECT* rectBig = GetRECTFromRect(guiMan->_guiElements["MULTIPLAYER"]->GetRect()); tex->SetRect(rectBig); delete rectBig; } else { guiMan->_guiElements["MULTIPLAYER"]->SetColor(XMFLOAT4(1, 0, 0, 1)); guiMan->_guiElements["MULTIPLAYER"]->SetScale(XMFLOAT2(1, 1)); } if(guiMan->_guiElements["EXIT"]->IsMouseHovering()|| menuOptions == MENU_OPTIONS::EXIT) { guiMan->_guiElements["EXIT"]->SetColor(XMFLOAT4(1, 1, 1, 1)); guiMan->_guiElements["EXIT"]->SetScale(XMFLOAT2(1.105f, 1.105f)); menuOptions = MENU_OPTIONS::EXIT; GUITexture* tex = (GUITexture*)(guiMan->_guiElements["Texture"]); RECT* rectBig = GetRECTFromRect(guiMan->_guiElements["EXIT"]->GetRect()); tex->SetRect(rectBig); delete rectBig; } else { guiMan->_guiElements["EXIT"]->SetColor(XMFLOAT4(0, 0, 0, 1)); guiMan->_guiElements["EXIT"]->SetScale(XMFLOAT2(1, 1)); } if(guiMan->_guiElements["SETTINGS"]->IsMouseHovering()|| menuOptions == MENU_OPTIONS::SETTINGS) { guiMan->_guiElements["SETTINGS"]->SetColor(XMFLOAT4(1, 1, 1, 1)); guiMan->_guiElements["SETTINGS"]->SetScale(XMFLOAT2(1.105f, 1.105f)); menuOptions = MENU_OPTIONS::SETTINGS; GUITexture* tex = (GUITexture*)(guiMan->_guiElements["Texture"]); RECT* rectBig = GetRECTFromRect(guiMan->_guiElements["SETTINGS"]->GetRect()); tex->SetRect(rectBig); delete rectBig; } else { guiMan->_guiElements["SETTINGS"]->SetColor(XMFLOAT4(0, 0, 0, 1)); guiMan->_guiElements["SETTINGS"]->SetScale(XMFLOAT2(1, 1)); } currstate = KeyboardInputProcess(); return currstate; }
// 天体信息的初始化, 包括材质, 纹理转换矩阵, 以及恒星的世界矩阵等 void SuperSolarSystemApp::InitStarInformation( ) { XMMATRIX I = XMMatrixIdentity( ); // // 初始化纹理转换矩阵, 由于大多是静态纹理, 所以直接初始化为单位阵 // for ( int i = 0; i < STARNUMBER; i++ ) { if ( WIREFENCE == i ) { XMStoreFloat4x4( &mTexTransform[i], XMMatrixScaling( 5.0f, 5.0f, 0.0f ) ); } else { XMStoreFloat4x4( &mTexTransform[i], I ); } } // // 初始化材质 // // 天体的材质 for ( int i = 0; i < STARNUMBER; i++ ) { if ( ICECUBE == i || METAL == i ) continue; mMat[i].Ambient = XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ); mMat[i].Diffuse = XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ); mMat[i].Specular = XMFLOAT4( 0.8f, 0.8f, 0.8f, 16.0f ); mMat[i].Reflect = XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ); // 太阳是自发光的 if ( SUN == i ) { mMat[i].Emissive = XMFLOAT4( 0.8f, 0.8f, 0.8f, 1.0f ); } else { mMat[i].Emissive = XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ); } } // 冰立方的材质 mMat[ICECUBE].Ambient = XMFLOAT4( 0.5f, 0.5f, 0.5f, 1.0f ); mMat[ICECUBE].Diffuse = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.5f ); mMat[ICECUBE].Specular = XMFLOAT4( 0.8f, 0.8f, 0.8f, 16.0f ); mMat[ICECUBE].Emissive = XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ); mMat[ICECUBE].Reflect = XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ); // 金属球的材质 mMat[METAL].Ambient = XMFLOAT4( 0.2f, 0.2f, 0.2f, 1.0f ); mMat[METAL].Diffuse = XMFLOAT4( 0.2f, 0.2f, 0.2f, 1.0f ); mMat[METAL].Specular = XMFLOAT4( 0.8f, 0.8f, 0.8f, 16.0f ); mMat[METAL].Emissive = XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ); mMat[METAL].Reflect = XMFLOAT4( 0.8f, 0.8f, 0.8f, 1.0f ); // // 初始化世界矩阵 // XMMATRIX scale; // 轨道 for ( int i = SUN; i < STARNUMBER; i++ ) { scale = XMMatrixScaling( starinfo[i].distanceToSun, starinfo[i].distanceToSun, starinfo[i].distanceToSun ); XMStoreFloat4x4( &mOrbitWorld[i], scale ); } // 太阳 scale = XMMatrixScaling( starinfo[SUN].equatorialRadius, starinfo[SUN].equatorialRadius, starinfo[SUN].equatorialRadius ); XMStoreFloat4x4( &mWorld[SUN], scale ); }
// ------------------------------------------------------- Cam::Cam() : quat(XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)), pos(XMFLOAT3(0.0f, 0.0f, -0.5f)), angle(90), near_z(0.5f), far_z(100.0f) {}
void UIDisplay::drawWindowText( ID3D11DeviceContext* device, UIWindow& window, TextManager& tm ) { UIWindow::Text* text; uint textCount; window.getText( &text, &textCount ); float x = 0.0f; float y = 0.0f; float len = static_cast<float>( strlen( text->message ) ) * FONTWIDTH; y = window.getPosition().y + (UIWINDOW_TITLE_BAR_HEIGHT / 2.0f) - ( FONTHEIGHT / 2.0f ); x = window.getPosition().x + ( window.getDimension().x / 2.0f ) - ( len / 2.0f ); XMFLOAT4 colors[3] = { XMFLOAT4(1,1,1,1), //Not selected: White XMFLOAT4(1,1,0,1), //Highlighted: Yellow XMFLOAT4(0,0,1,1) //Selected: Blue }; D3DX11_TECHNIQUE_DESC techDesc; mTechnique->GetDesc( &techDesc ); for(ushort p = 0; p < techDesc.Passes; ++p) { //Draw title mTechnique->GetPassByIndex(p)->Apply(0, device); tm.drawString( device, text->message, x, y ); float len = 0.0f; //Draw tab names for(uint i = 0; i < window.getTabCount(); i++) { tm.drawString( device, window.getTab(i).name, window.getPosition().x +(mBorderDimension * 2.0f) + len, window.getPosition().y + (UIWINDOW_TITLE_BAR_HEIGHT * 2.0f) - ( FONTHEIGHT * 1.5f ), i == window.getCurrentTab() ? colors[2] : window.getTab(i).highlighted ? colors[1] : colors[0]); len += static_cast<float>(strlen(window.getTab(i).name)) * FONTWIDTH + ( FONTWIDTH / 2.0f ); } //Draw UI Text UIWindow::Tab& t = window.getTab( window.getCurrentTab() ); //Loop through and build elements in the current tab for(int i = 0; i < t.elementCount; i++) { if( t.elements[i]->getElemType() == UIElement::ElemType::TextBox ) { UIElement::Text* text; uint textCount; t.elements[i]->getText( &text, &textCount ); for(uint l = 0; l < textCount; l++) { tm.drawString( device, text[l].message, t.elements[i]->getPosition().x + text[l].offset.x + window.getPosition().x + FONTWIDTH / 2.0f, t.elements[i]->getPosition().y + text[l].offset.y + window.getPosition().y + (FONTHEIGHT / 2.0f), colors[0] ); } } else if( t.elements[i]->getElemType() == UIElement::ElemType::OptionBox ) { UIOptionBox* box = (UIOptionBox*)(t.elements[i]); for(uint o = 0; o < box->getNumOptions(); o++) { char* opt = box->getOption(o); uint optIndex = o + ( box->getScrollIndex() - box->getNumOptions() ); tm.drawString( device, opt, t.elements[i]->getPosition().x + window.getPosition().x + 0.02f, t.elements[i]->getPosition().y + window.getPosition().y + ( ( FONTHEIGHT + 0.04f ) * static_cast<float>(o) ), colors[ optIndex == box->getSelected() ? 2 : optIndex == box->getHighlighted() ? 1 : 0 ] ); } } else { UIElement::Text* text; uint tCount; t.elements[i]->getText(&text, &tCount ); //Center the text float xOffset = (t.elements[i]->getDimension().x / 2.0f) - (static_cast<float>(strlen(text->message)) * FONTWIDTH / 2.0f); float yOffset = (t.elements[i]->getDimension().y / 2.0f) - FONTHEIGHT / 2.0f; //Draw the text bro tm.drawString( device, text->message, t.elements[i]->getPosition().x + window.getPosition().x + xOffset + text->offset.x, t.elements[i]->getPosition().y + window.getPosition().y + yOffset + text->offset.y, colors[ t.elements[i]->getSelectedState() ]); } //If it is a drop menu, draw the options if( t.elements[i]->getElemType() == UIElement::ElemType::DropMenu ) { UIDropMenu* d = *(UIDropMenu**)(t.elements + i); float tx = t.elements[i]->getPosition().x + window.getPosition().x + (FONTWIDTH / 2.0f); float ty = t.elements[i]->getPosition().y + window.getPosition().y + (FONTHEIGHT / 2.0f); if( d->isDropped() ) { for(uint o = 0; o < d->getOptionCount(); o++) { tm.drawString( device, d->getOption(o), tx, ty, d->getSelectedOption() == o ? colors[2] : d->getHightlightedOption() == o ? colors[1] : colors[0] ); ty += 0.1f; } } else { tm.drawString( device, d->getOption(d->getSelectedOption()), tx, ty, colors[2]); } } else if( t.elements[i]->getElemType() == UIElement::ElemType::InputBox ) { UIInputBox* d = *(UIInputBox**)(t.elements + i); float tx = t.elements[i]->getPosition().x + window.getPosition().x + (FONTWIDTH / 2.0f); float ty = t.elements[i]->getPosition().y + window.getPosition().y + (FONTHEIGHT / 2.0f); tm.drawString( device, d->getInput(), tx, ty, colors[0]); } } } }
void LightAlphaMapShader::SetShaderParameters(ID3D11DeviceContext* deviceContext, const XMMATRIX &worldMatrix, const XMMATRIX &viewMatrix, const XMMATRIX &projectionMatrix, const sz::Material &mat) { HRESULT result; D3D11_MAPPED_SUBRESOURCE mapped_resource; sz::MatrixBufferType* data_ptr; unsigned int bufferNumber; XMMATRIX tworld, tview, tproj; // Transpose the matrices to prepare them for the shader. tworld = XMMatrixTranspose(worldMatrix); tview = XMMatrixTranspose(viewMatrix); tproj = XMMatrixTranspose(projectionMatrix); // Lock the constant buffer so it can be written to. result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource); // Get a pointer to the data in the constant buffer. data_ptr = (sz::MatrixBufferType*)mapped_resource.pData; // Copy the matrices into the constant buffer. data_ptr->world = tworld;// worldMatrix; data_ptr->view = tview; data_ptr->projection = tproj; // Unlock the constant buffer. deviceContext->Unmap(m_matrixBuffer, 0); // Set the position of the constant buffer in the vertex shader. bufferNumber = 0; // Now set the constant buffer in the vertex shader with the updated values. deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer); deviceContext->DSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer); // Assign the material data sz::MaterialBufferType *mat_buff_ptr; result = deviceContext->Map(material_buf_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource); // Get a ptr to the data in the constant buffer mat_buff_ptr = (sz::MaterialBufferType *)mapped_resource.pData; // Set its data mat_buff_ptr->ambient = XMFLOAT4(mat.ambient[0], mat.ambient[1], mat.ambient[2], mat.dissolve); mat_buff_ptr->diffuse = XMFLOAT4(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2], mat.dissolve); mat_buff_ptr->specular = XMFLOAT4(mat.specular[0], mat.specular[1], mat.specular[2], mat.dissolve); mat_buff_ptr->transmittance = XMFLOAT4(mat.transmittance[0], mat.transmittance[1], mat.transmittance[2], 1.f); mat_buff_ptr->emission = XMFLOAT4(mat.emission[0], mat.emission[1], mat.emission[2], mat.dissolve); mat_buff_ptr->shininess = mat.shininess; mat_buff_ptr->ior = mat.ior; mat_buff_ptr->dissolve = mat.dissolve; mat_buff_ptr->illum = mat.illum; // Unlock the constant buffer deviceContext->Unmap(material_buf_, 0); // Set the constant buffer index in the pixel shader deviceContext->PSSetConstantBuffers(1, 1, &material_buf_); // Set shader resources for shadow maps //for (size_t i = 0; i < kNumLights; ++i) { // std::string name; // std::stringstream ss; // ss << "target_depth_" << i; // name = ss.str(); // ID3D11ShaderResourceView * texture = // Texture::Inst()->GetTexture(name.c_str()); // deviceContext->PSSetShaderResources(2 + i, 1, &texture); //} ID3D11ShaderResourceView * texture = Texture::Inst()->GetTexture(mat.diffuse_texname_crc); ID3D11ShaderResourceView * texture_alpha = Texture::Inst()->GetTexture(mat.alpha_texname_crc); // Set shader texture resource in the pixel shader. deviceContext->PSSetShaderResources(0, 1, &texture); deviceContext->PSSetShaderResources(1, 1, &texture_alpha); }
void LightClass::SetDiffuseColor(float red, float green, float blue, float alpha) { m_diffuseColor = XMFLOAT4(red, green, blue, alpha); return; }
void SpecularLightingDemo::UpdateDirectionalLight(const GameTime& gameTime, const GamePad::State& gamePadState) { float elapsedTime = gameTime.ElapsedGameTimeSeconds().count(); static float lightr = mPSCBufferPerFrame.LightColor.x; static float lightg = mPSCBufferPerFrame.LightColor.y; static float lightb = mPSCBufferPerFrame.LightColor.z; //Color if (mKeyboard->IsKeyDown(Keys::NumPad4) || mGamePad->IsButtonDown(GamePadButtons::Y)) { lightr = max(0.0f, min(lightr + elapsedTime, 1.0f)); mPSCBufferPerFrame.LightColor = XMFLOAT4(lightr, lightg, lightb, 1.0f); } else if (mKeyboard->IsKeyDown(Keys::D4) || mGamePad->IsButtonDown(GamePadButtons::B)) { lightr = max(0.0f, min(lightr - elapsedTime, 1.0f)); mPSCBufferPerFrame.LightColor = XMFLOAT4(lightr, lightg, lightb, 1.0f); } if (mKeyboard->IsKeyDown(Keys::NumPad5) || mGamePad->IsButtonDown(GamePadButtons::Y)) { lightg = max(0.0f, min(lightg + elapsedTime, 1.0f)); mPSCBufferPerFrame.LightColor = XMFLOAT4(lightr, lightg, lightb, 1.0f); } else if (mKeyboard->IsKeyDown(Keys::D5) || mGamePad->IsButtonDown(GamePadButtons::B)) { lightg = max(0.0f, min(lightg - elapsedTime, 1.0f)); mPSCBufferPerFrame.LightColor = XMFLOAT4(lightr, lightg, lightb, 1.0f); } if (mKeyboard->IsKeyDown(Keys::NumPad6) || mGamePad->IsButtonDown(GamePadButtons::Y)) { lightb = max(0.0f, min(lightb + elapsedTime, 1.0f)); mPSCBufferPerFrame.LightColor = XMFLOAT4(lightr, lightg, lightb, 1.0f); } else if (mKeyboard->IsKeyDown(Keys::D6) || mGamePad->IsButtonDown(GamePadButtons::B)) { lightb = max(0.0f, min(lightb - elapsedTime, 1.0f)); mPSCBufferPerFrame.LightColor = XMFLOAT4(lightr, lightg, lightb, 1.0f); } if (mUseGamePadForDirectionalLight) { // Rotate directional light XMFLOAT2 rotationAmount; rotationAmount.x = -gamePadState.thumbSticks.rightX * LightRotationRate.x * elapsedTime; rotationAmount.y = gamePadState.thumbSticks.rightY * 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); mPSCBufferPerFrame.LightDirection = mDirectionalLight->DirectionToLight(); mGame->Direct3DDeviceContext()->UpdateSubresource(mPSConstantBufferPF.Get(), 0, nullptr, &mPSCBufferPerFrame, 0, 0); } } }
void wiBULLET::addSphere(float rad, const XMFLOAT3& pos , float newMass, float newFriction, float newRestitution, float newDamping, bool kinematic){ ///create a few basic rigid bodies /*btCollisionShape* groundShape = new btshape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.))); collisionShapes.push_back(groundShape); btTransform groundTransform; groundTransform.setIdentity(); groundTransform.setOrigin(btVector3(0,-56,0)); { btScalar mass(0.); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0,0,0); if (isDynamic) groundShape->calculateLocalInertia(mass,localInertia); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia); btRigidBody* body = new btRigidBody(rbInfo); //add the body to the dynamics world dynamicsWorld->addRigidBody(body); } { //create a dynamic rigidbody //btCollisionShape* colShape = new btshape(btVector3(1,1,1)); btCollisionShape* colShape = new btSphereShape(btScalar(1.)); collisionShapes.push_back(colShape); /// Create Dynamic Objects btTransform startTransform; startTransform.setIdentity(); btScalar mass(1.f); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0,0,0); if (isDynamic) colShape->calculateLocalInertia(mass,localInertia); startTransform.setOrigin(btVector3(2,10,0)); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia); btRigidBody* body = new btRigidBody(rbInfo); dynamicsWorld->addRigidBody(body); }*/ btCollisionShape* shape = new btSphereShape(btScalar(rad)); shape->setMargin(btScalar(0.05)); collisionShapes.push_back(shape); btTransform shapeTransform; shapeTransform.setIdentity(); shapeTransform.setOrigin(btVector3(pos.x,pos.y,pos.z)); { btScalar mass(newMass); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f && !kinematic); btVector3 localInertia(0,0,0); if (isDynamic) shape->calculateLocalInertia(mass,localInertia); else mass=0; //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(shapeTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,shape,localInertia); rbInfo.m_friction=newFriction; rbInfo.m_restitution=newRestitution; rbInfo.m_linearDamping=newDamping; rbInfo.m_angularDamping = newDamping; btRigidBody* body = new btRigidBody(rbInfo); if(kinematic) body->setCollisionFlags( body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); body->setActivationState(DISABLE_DEACTIVATION); //add the body to the dynamics world dynamicsWorld->addRigidBody(body); if (body && body->getMotionState()) { btTransform trans; body->getMotionState()->getWorldTransform(trans); btQuaternion nRot = trans.getRotation(); btVector3 nPos = trans.getOrigin(); transforms.push_back(new PhysicsTransform( XMFLOAT4(nRot.getX(),nRot.getY(),nRot.getZ(),nRot.getW()),XMFLOAT3(nPos.getX(),nPos.getY(),nPos.getZ())) ); } } }
bool DX11ViewportRenderer::drawSurface( const MDagPath &dagPath, bool active, bool templated) { bool drewSurface = false; if ( !dagPath.hasFn( MFn::kMesh )) { MMatrix matrix = dagPath.inclusiveMatrix(); MFnDagNode dagNode(dagPath); MBoundingBox box = dagNode.boundingBox(); float color[3] = {0.6f, 0.3f, 0.0f}; if (active) { color[0] = 1.0f; color[1] = 1.0f; color[2] = 1.0f; } else if (templated) { color[0] = 1.0f; color[1] = 0.686f; color[2] = 0.686f; } drawBounds( matrix, box, color); return true; } if ( dagPath.hasFn( MFn::kMesh )) { MMatrix matrix = dagPath.inclusiveMatrix(); MFnDagNode dagNode(dagPath); // Look for any hardware shaders which can draw D3D first. // bool drewWithHwShader = false; { MFnMesh fnMesh(dagPath); MObjectArray sets; MObjectArray comps; unsigned int instanceNum = dagPath.instanceNumber(); if (!fnMesh.getConnectedSetsAndMembers(instanceNum, sets, comps, true)) MGlobal::displayError("ERROR : MFnMesh::getConnectedSetsAndMembers"); for ( unsigned i=0; i<sets.length(); i++ ) { MObject set = sets[i]; MObject comp = comps[i]; MStatus status; MFnSet fnSet( set, &status ); if (status == MS::kFailure) { MGlobal::displayError("ERROR: MFnSet::MFnSet"); continue; } MObject shaderNode = findShader(set); if (shaderNode != MObject::kNullObj) { MPxHardwareShader * hwShader = MPxHardwareShader::getHardwareShaderPtr( shaderNode ); if (hwShader) { const MRenderProfile & profile = hwShader->profile(); if (profile.hasRenderer( MRenderProfile::kMayaD3D)) { // Render a Maya D3D hw shader here.... //printf("Found a D3D hw shader\n"); //drewWithHwShader = true; } } } } } // Get the geometry buffers for this bad boy and render them D3DGeometry* Geometry = m_resourceManager.getGeometry( dagPath, m_pD3DDevice); if( Geometry) { // Transform from object to world space // XMMATRIX objectToWorld = XMMATRIX ( (float)matrix.matrix[0][0], (float)matrix.matrix[0][1], (float)matrix.matrix[0][2], (float)matrix.matrix[0][3], (float)matrix.matrix[1][0], (float)matrix.matrix[1][1], (float)matrix.matrix[1][2], (float)matrix.matrix[1][3], (float)matrix.matrix[2][0], (float)matrix.matrix[2][1], (float)matrix.matrix[2][2], (float)matrix.matrix[2][3], (float)matrix.matrix[3][0], (float)matrix.matrix[3][1], (float)matrix.matrix[3][2], (float)matrix.matrix[3][3] ); FixedFunctionConstants cb; if (!drewWithHwShader) { // Get material properties for shader associated with mesh // // 1. Try to draw with the sample internal programmable shader bool drewGeometryWithShader = false; // 2. Draw with fixed function shader if (!drewGeometryWithShader) { // Set up a default material, just in case there is none. // float diffuse[3]; if (active) { if (templated) { m_pD3DDeviceCtx->RSSetState( m_pWireframeRS ); diffuse[0] = 1.0f; diffuse[1] = 0.686f; diffuse[2] = 0.686f; } else { m_pD3DDeviceCtx->RSSetState( m_pNormalRS ); diffuse[0] = 0.6f; diffuse[1] = 0.6f; diffuse[2] = 0.6f; } } else { if (templated) { m_pD3DDeviceCtx->RSSetState( m_pWireframeRS ); diffuse[0] = 1.0f; diffuse[1] = 0.686f; diffuse[2] = 0.686f; } else { m_pD3DDeviceCtx->RSSetState( m_pNormalRS ); diffuse[0] = 0.5f; diffuse[1] = 0.5f; diffuse[2] = 0.5f; } } // Set constant buffer XMVECTOR det; cb.wvIT = XMMatrixInverse( &det, objectToWorld * m_currentViewMatrix ); cb.wvp = XMMatrixTranspose( objectToWorld * m_currentViewMatrix * m_currentProjectionMatrix ); cb.wv = XMMatrixTranspose( objectToWorld * m_currentViewMatrix ); cb.lightDir = XMFLOAT4( 0.0f, 0.0f, 1.0f, 0.0f ); cb.lightColor = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.0f ); cb.ambientLight = XMFLOAT4( 0.2f, 0.2f, 0.2f, 0.0f ); cb.diffuseMaterial = XMFLOAT4( diffuse[0], diffuse[1], diffuse[2], 0.0f ); cb.specularColor = XMFLOAT4( 0.2f, 0.2f, 0.2f, 0.0f ); cb.diffuseCoeff = 1.0f; cb.shininess = 16.0f; cb.transparency = 1.0f; m_pD3DDeviceCtx->UpdateSubresource( m_pFixedFunctionConstantBuffer, 0, NULL, &cb, 0, 0 ); // get shader SurfaceEffectItemList::const_iterator it = m_resourceManager.getSurfaceEffectItemList().find( "Maya_fixedFunction" ); if ( it == m_resourceManager.getSurfaceEffectItemList().end() ) return false; const SurfaceEffectItem* sei = it->second; // bind shaders m_pD3DDeviceCtx->VSSetShader( sei->fVertexShader, NULL, 0 ); m_pD3DDeviceCtx->VSSetConstantBuffers( 0, 1, &m_pFixedFunctionConstantBuffer ); m_pD3DDeviceCtx->IASetInputLayout( sei->fInputLayout ); m_pD3DDeviceCtx->PSSetShader( sei->fPixelShader, NULL, 0 ); m_pD3DDeviceCtx->PSSetConstantBuffers( 0, 1, &m_pFixedFunctionConstantBuffer ); Geometry->Render( m_pD3DDeviceCtx ); drewSurface = true; } } // Draw wireframe on top // if ( drewSurface && active ) { bool drawActiveWithBounds = false; if (drawActiveWithBounds) { MBoundingBox box = dagNode.boundingBox(); float color[3] = {1.0f, 1.0f, 1.0f}; drawBounds( matrix, box, color ); } else { cb.lightColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); cb.ambientLight = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.0f ); cb.diffuseMaterial = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.0f ); cb.specularColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); m_pD3DDeviceCtx->UpdateSubresource( m_pFixedFunctionConstantBuffer, 0, NULL, &cb, 0, 0 ); m_pD3DDeviceCtx->RSSetState( m_pWireframeRS ); Geometry->Render( m_pD3DDeviceCtx ); } } } // If Geometry } return drewSurface; }
void Hill::init_buffer(ID3D11Device *pD3D11Device, ID3D11DeviceContext *pD3D11DeviceContext) { HRESULT hr; d3d::Geometry::MeshData gridMesh; m_Geometry.CreateGrid(160.0f, 160.0f, 50, 50, gridMesh); /////////////////////////////Vertex Buffer////////////////////////////// m_VertexCount = gridMesh.VertexData.size(); m_VertexData.resize(m_VertexCount); for(size_t i = 0; i < m_VertexCount; ++i) { XMFLOAT3 p = gridMesh.VertexData[i].Pos; p.y = GetHeight(p.x, p.z); m_VertexData[i].Pos = p; m_VertexData[i].Normal = GetHillNormal(p.x, p.z); m_VertexData[i].TexCoord = gridMesh.VertexData[i].Tex; } D3D11_BUFFER_DESC landVBDesc; landVBDesc.Usage = D3D11_USAGE_IMMUTABLE; landVBDesc.ByteWidth = sizeof(Vertex) * m_VertexCount; landVBDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; landVBDesc.CPUAccessFlags = 0; landVBDesc.MiscFlags = 0; landVBDesc.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA landVBO; landVBO.pSysMem = &m_VertexData[0]; hr = pD3D11Device->CreateBuffer(&landVBDesc, &landVBO, &m_pLandVB); //DebugHR(hr); /////////////////////////////Index Buffer////////////////////////////// m_IndexCount = gridMesh.IndexData.size(); D3D11_BUFFER_DESC landIBDesc; landIBDesc.Usage = D3D11_USAGE_IMMUTABLE; landIBDesc.ByteWidth = sizeof(UINT) * m_IndexCount; landIBDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; landIBDesc.CPUAccessFlags = 0; landIBDesc.MiscFlags = 0; landIBDesc.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA landIBO; landIBO.pSysMem = &gridMesh.IndexData[0]; hr = pD3D11Device->CreateBuffer(&landIBDesc, &landIBO, &m_pLandIB); //DebugHR(hr); ////////////////////////////////Const Buffer////////////////////////////////////// m_Wave.Init(200, 200, 0.8f, 0.03f, 3.25f, 0.4f); D3D11_BUFFER_DESC waveVBDesce; waveVBDesce.Usage = D3D11_USAGE_DYNAMIC; waveVBDesce.ByteWidth = sizeof(Vertex) * m_Wave.VertexCount(); waveVBDesce.BindFlags = D3D11_BIND_VERTEX_BUFFER; waveVBDesce.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; waveVBDesce.MiscFlags = 0; waveVBDesce.StructureByteStride = 0; hr = pD3D11Device->CreateBuffer(&waveVBDesce, NULL, &m_pWaveVB); //DebugHR(hr); /////////////////////////////Index Buffer////////////////////////////// std::vector<UINT> indices(3 * m_Wave.TriangleCount() ); // 3 indices per face // Iterate over each quad. UINT m = m_Wave.RowCount(); UINT n = m_Wave.ColumnCount(); int k = 0; for(UINT i = 0; i < m-1; ++i) { for(DWORD j = 0; j < n-1; ++j) { indices[k] = i*n+j; indices[k+1] = i*n+j+1; indices[k+2] = (i+1)*n+j; indices[k+3] = (i+1)*n+j; indices[k+4] = i*n+j+1; indices[k+5] = (i+1)*n+j+1; k += 6; // next quad } } D3D11_BUFFER_DESC waveIBDesc; waveIBDesc.Usage = D3D11_USAGE_IMMUTABLE; waveIBDesc.ByteWidth = sizeof(UINT) * indices.size(); waveIBDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; waveIBDesc.CPUAccessFlags = 0; waveIBDesc.MiscFlags = 0; waveIBDesc.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA waveIBO; waveIBO.pSysMem = &indices[0]; hr = pD3D11Device->CreateBuffer(&waveIBDesc, &waveIBO, &m_pWaveIB); //DebugHR(hr); // Directional light. m_DirLight.Ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); m_DirLight.Diffuse = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); m_DirLight.Specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); m_DirLight.Direction = XMFLOAT3(0.57735f, -0.57735f, 0.57735f); //Point light--position is changed every frame to animate in UpdateScene function. m_PointLight.Ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f); m_PointLight.Diffuse = XMFLOAT4(0.7f, 0.7f, 0.7f, 1.0f); m_PointLight.Specular = XMFLOAT4(0.7f, 0.7f, 0.7f, 1.0f); m_PointLight.Att = XMFLOAT3(0.0f, 0.1f, 0.0f); m_PointLight.Range = 25.0f; //Spot light--position and direction changed every frame to animate in UpdateScene function. m_SpotLight.Ambient = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f); m_SpotLight.Diffuse = XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f); m_SpotLight.Specular = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); m_SpotLight.Att = XMFLOAT3(1.0f, 0.0f, 0.0f); m_SpotLight.Spot = 96.0f; m_SpotLight.Range = 10000.0f; m_LandMat.Ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); m_LandMat.Diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); m_LandMat.Specular = XMFLOAT4(0.2f, 0.2f, 0.2f, 16.0f); m_WavesMat.Ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); m_WavesMat.Diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); m_WavesMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 32.0f); }