void Camera::SetOrthoProjection(float X1, float X2, float Y1, float Y2, float ZNear, float ZFar) { if(X2>X1 && Y2>Y1 && ZFar>ZNear) mProjectionMatrix=XMMatrixOrthographicOffCenterLH(X1,X2,Y2,Y1,ZNear,ZFar); else Log::Error("Camera::SetOrthoProjection: check parametr's"); }
void DemoApp::BuildShadowMapMatrices() { //Calculate the radius of the scene's bounding sphere. Approximately use the half of ground plane diagonal. float aabbRadius = sqrt(grndLength * grndLength + grndWidth * grndWidth) / 2.0f ; //Set up light parameter XMVECTOR lightDir = XMLoadFloat3(&mDirLight.Direction); XMVECTOR lightPos = -1.0f * lightDir * aabbRadius; XMFLOAT3 tar = XMFLOAT3(0.0f, 0.0f, 0.0f); XMVECTOR targetPos = XMLoadFloat3(&tar); XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); mLightView = XMMatrixLookAtLH(lightPos, targetPos, up); // Transform bounding sphere to light space. XMFLOAT3 aabbCenterLightSpace; XMStoreFloat3(&aabbCenterLightSpace, XMVector3TransformCoord(targetPos, mLightView)); //// Ortho frustum in light space encloses scene. float l = aabbCenterLightSpace.x - aabbRadius; float b = aabbCenterLightSpace.y - aabbRadius; float n = aabbCenterLightSpace.z - aabbRadius; float r = aabbCenterLightSpace.x + aabbRadius; float t = aabbCenterLightSpace.y + aabbRadius; float f = aabbCenterLightSpace.z + aabbRadius; mLightProj = XMMatrixOrthographicOffCenterLH(l, r, b, t, n, f); // Transform NDC space [-1,+1]^2 to texture space [0,1]^2 mLightViewport = XMMATRIX( 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.0f, 1.0f); mLightVPT = mLightView*mLightProj*mLightViewport; }
void InClassProj::OnResize() { D3DApp::OnResize(); // The window resized, so update the aspect ratio and recompute the projection matrix. XMMATRIX P = XMMatrixPerspectiveFovLH(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f); XMStoreFloat4x4(&mProj, P); P = XMMatrixOrthographicOffCenterLH(0.0f, mClientWidth, 0.0f, mClientHeight, 0.0001f, 1000.0f); XMStoreFloat4x4(&m2DProj, P); }
void OrthographicCamera::SetProjParams(_In_ float minX, _In_ float minY, _In_ float maxX, _In_ float maxY, _In_ float fNearPlane, _In_ float fFarPlane) { Assert_(maxX > minX && maxY > minY); m_fxMin = minX; m_fyMin = minY; m_fxMax = maxX; m_fyMax = maxY; m_fNearPlane = fNearPlane; m_fFarPlane = fFarPlane; m_mProj = XMMatrixOrthographicOffCenterLH(m_fxMin, m_fxMax, m_fyMin, m_fyMax, m_fNearPlane, m_fFarPlane); }
void Projekt::buildShadowTransform() { // Only first "main" light casts a shadow // So get light direction and position from first light XMVECTOR lightDir = XMLoadFloat3(&mDirLights[0].Direction); XMVECTOR lightPos = -2.0f*mSceneBounds.Radius*lightDir; XMVECTOR targetPos = XMLoadFloat3(&mSceneBounds.Center); XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); XMMATRIX V = XMMatrixLookAtLH(lightPos, targetPos, up); // Transform bounding sphere to light space XMFLOAT3 sphereCenterLS; XMStoreFloat3(&sphereCenterLS, XMVector3TransformCoord(targetPos, V)); // Orthogonal frustum in light space encloses scene float l = sphereCenterLS.x - mSceneBounds.Radius; float b = sphereCenterLS.y - mSceneBounds.Radius; float n = sphereCenterLS.z - mSceneBounds.Radius; float r = sphereCenterLS.x + mSceneBounds.Radius; float t = sphereCenterLS.y + mSceneBounds.Radius; float f = sphereCenterLS.z + mSceneBounds.Radius; XMMATRIX P = XMMatrixOrthographicOffCenterLH(l, r, b, t, n, f); // Transform NDC space [-1,+1]^2 to texture space [0,1]^2 XMMATRIX T( 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.0f, 1.0f); XMMATRIX S = V*P*T; XMStoreFloat4x4(&mLightView, V); XMStoreFloat4x4(&mLightProj, P); XMStoreFloat4x4(&mShadowTransform, S); }
void CDirect3D::SetViewport() { XMMATRIX matIdentity; XMMATRIX matProjection; matProjection = XMMatrixOrthographicOffCenterLH(0.0f,1.0f,0.0f,1.0f,0.0f,1.0f); matIdentity = XMMatrixIdentity(); pDevice->SetTransform(D3DTS_WORLD,(D3DMATRIX*)&matIdentity); pDevice->SetTransform(D3DTS_VIEW, (D3DMATRIX*)&matIdentity); pDevice->SetTransform(D3DTS_PROJECTION, (D3DMATRIX*)&matProjection); RECT drawRect = CalculateDisplayRect(afterRenderWidth,afterRenderHeight,dPresentParams.BackBufferWidth,dPresentParams.BackBufferHeight); D3DVIEWPORT9 viewport; viewport.X = drawRect.left; viewport.Y = drawRect.top; viewport.Height = drawRect.bottom - drawRect.top; viewport.Width = drawRect.right - drawRect.left; viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; HRESULT hr = pDevice->SetViewport(&viewport); SetupVertices(); }
// сброс камеры bool Camera::Reset() { // пересоздать матрицу проеции float ratio = (float)Mediator::winDimentions->x / Mediator::winDimentions->y; projMatrix = XMMatrixPerspectiveFovLH(XM_PIDIV4, ratio, NearFarZ.x, NearFarZ.y); // пересоздать матрицу ортографической проекции orthoMatrix = XMMatrixOrthographicOffCenterLH(0.0f, (float)Mediator::winDimentions->x, (float)Mediator::winDimentions->y, 0.0f, NearFarOZ.x, NearFarOZ.y); // запись в буфер шейдера BR(Mediator::shader->SetResetBuffer(orthoMatrix)); // перестроить фрустум BR(RebuildFrustum()); // передача в шейдер XMVECTOR focus_JP = { camFocus.x - camPosition.x, camFocus.y - camPosition.y, camFocus.z - camPosition.z }; XMMATRIX V_JP = XMMatrixLookAtLH(XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f), focus_JP, camUp); BR(Mediator::shader->SetCamBuffer(V_JP * projMatrix, XMFLOAT4(camPosition.x, camPosition.y, camPosition.z, 1.0f), XMFLOAT4(camFocus.x, camFocus.y, camFocus.z, 1.0f))); return true; }
// конструктор камеры Camera::Camera(bool* result) { azimuth = -1.2f; // создать матрицу проекции float ratio = (float)Mediator::winDimentions->x / Mediator::winDimentions->y; projMatrix = XMMatrixPerspectiveFovLH(XM_PIDIV4, ratio, NearFarZ.x, NearFarZ.y); // создать матрицу ортографической проекции orthoMatrix = XMMatrixOrthographicOffCenterLH(0.0f, (float)Mediator::winDimentions->x, (float)Mediator::winDimentions->y, 0.0f, NearFarOZ.x, NearFarOZ.y); // запись в буфер шейдера BRR(Mediator::shader->SetResetBuffer(orthoMatrix)); // вычисление координат камеры camPosition.x = radius * sin(azimuth) * cos(pitch); camPosition.z = radius * cos(azimuth) * cos(pitch); camPosition.y = radius * sin(pitch); camPosition += camFocus; Mediator::camera = this; *result = true; }
void OrthographicCamera::CreateProjection() { m_mProj = XMMatrixOrthographicOffCenterLH(m_fxMin, m_fxMax, m_fyMin, m_fyMax, m_fNearPlane, m_fFarPlane); //viewProjection = m_mProj * m_mProj; }
void glOrtho (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar) { XMMATRIX tmp = XMMatrixOrthographicOffCenterLH(left, right, bottom, top, zNear, zFar); CURRENT_MATRIX_STACK = tmp * CURRENT_MATRIX_STACK; current_matrix->dirty = 1; }
// Draw - must be positioned after all the controls are defined //-------------------------------------------------------------------------------- void CPUTGuiControllerDX11::Draw(ID3D11DeviceContext *pImmediateContext) { HEAPCHECK; if( 0 != GetNumberOfControlsInPanel()) { SetGUIDrawingState(pImmediateContext); } else { return; } ID3D11VertexShader *pVertexShader = mpGUIVertexShader->GetNativeVertexShader(); ID3D11PixelShader *pPixelShader = mpGUIPixelShader->GetNativePixelShader(); // check and see if any of the controls resized themselves int ControlCount=GetNumberOfControlsInPanel(); bool ResizingNeeded = false; for(int ii=0; ii<ControlCount; ii++) { CPUTControl *pControl = mControlPanelIDList[mActiveControlPanelSlotID]->mControlList[ii]; if(true == pControl->ControlResizedItself()) { ResizingNeeded = true; pControl->ControlResizingHandled(); } } // if any of the controls resized, then re-do the autoarrangment if(true == ResizingNeeded) { this->Resize(); } // Now check to see if any controls' graphics are dirty for(int ii=0; ii<ControlCount; ii++) { CPUTControl *pControl = mControlPanelIDList[mActiveControlPanelSlotID]->mControlList[ii]; if(true == pControl->ControlGraphicsDirty()) { mUberBufferDirty = true; break; } } // if any of the controls have announced they are dirty, then rebuild the mirror buffer and update the GFX buffer if(mUberBufferDirty) { // if a resize was flagged, do it now. if(mRecalculateLayout) { RecalculateLayout(); } // 'clear' the buffer by resetting the pointer to the head mUberBufferIndex = 0; mTextUberBufferIndex = 0; mFocusedControlBufferIndex = 0; mFocusedControlTextBufferIndex = 0; int ii=0; while(ii<GetNumberOfControlsInPanel()) { CPUTControl *pControl = mControlPanelIDList[mActiveControlPanelSlotID]->mControlList[ii]; // don't draw the focus control - draw it last so it stays on 'top' if(mpFocusControl != pControl) { switch(pControl->GetType()) { case CPUT_BUTTON: ((CPUTButton*)pControl)->DrawIntoBuffer(mpMirrorBuffer, &mUberBufferIndex, mUberBufferMax, mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_CHECKBOX: ((CPUTCheckbox*)pControl)->DrawIntoBuffer(mpMirrorBuffer, &mUberBufferIndex, mUberBufferMax, mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_SLIDER: ((CPUTSlider*)pControl)->DrawIntoBuffer(mpMirrorBuffer, &mUberBufferIndex, mUberBufferMax, mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_DROPDOWN: ((CPUTDropdown*)pControl)->DrawIntoBuffer(mpMirrorBuffer, &mUberBufferIndex, mUberBufferMax, mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_STATIC: ((CPUTText*)pControl)->DrawIntoBuffer(mpTextMirrorBuffer, &mTextUberBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; } } ii++; HEAPCHECK } // do the 'focused' control last so it stays on top (i.e. dropdowns) if(mpFocusControl) { switch(mpFocusControl->GetType()) { case CPUT_BUTTON: ((CPUTButton*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlBufferIndex, mUberBufferMax, mpFocusedControlTextMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_CHECKBOX: ((CPUTCheckbox*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlBufferIndex, mUberBufferMax, mpFocusedControlTextMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_SLIDER: ((CPUTSlider*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlBufferIndex, mUberBufferMax, mpFocusedControlTextMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_DROPDOWN: ((CPUTDropdown*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlBufferIndex, mUberBufferMax, mpFocusedControlTextMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; case CPUT_STATIC: ((CPUTText*)mpFocusControl)->DrawIntoBuffer(mpFocusedControlMirrorBuffer, &mFocusedControlTextBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); break; } } // update the uber-buffers with the control graphics UpdateUberBuffers(pImmediateContext); // Clear dirty flag on uberbuffer mUberBufferDirty = false; } HEAPCHECK // calculate the fps double elapsed = mpFPSTimer->GetElapsedTime(); double fps = 1.0 / elapsed; mLastFPS = (float) fps; // if we're drawing the FPS counter - update that // We do this independently of uber-buffer updates since we'll have FPS updates every frame, // but likely not have control updates every frame if(mbDrawFPS) { // calculate the time elapsed since last frame bool UberBufferWasDirty = mUberBufferDirty; cString Data; { wchar_t wcstring[CPUT_MAX_STRING_LENGTH]; swprintf_s(&wcstring[0], CPUT_MAX_STRING_LENGTH, _L("%.2f"), fps); Data=wcstring; } // build the FPS string cString FPS = _L("FPS: ")+Data; mpFPSCounter->SetText(FPS); // 'draw' the string into the buffer mFPSBufferIndex = 0; mpFPSCounter->DrawIntoBuffer(mpFPSMirrorBuffer, &mFPSBufferIndex, CPUT_GUI_BUFFER_STRING_SIZE); // update the DirectX vertex buffer ASSERT(CPUT_GUI_BUFFER_STRING_SIZE > mFocusedControlTextBufferIndex, _L("CPUT GUI: Too many strings for default-sized uber-buffer. Increase CPUT_GUI_BUFFER_STRING_SIZE")); pImmediateContext->UpdateSubresource(mpFPSDirectXBuffer, 0, NULL, mpFPSMirrorBuffer, mFPSBufferIndex*sizeof(CPUTGUIVertex), 0); // start next frame timer mpFPSTimer->StartTimer(); if(false == UberBufferWasDirty) { mUberBufferDirty = false; } } // set up orthographic display int windowWidth, windowHeight; GUIConstantBufferVS ConstantBufferMatrices; float znear = 0.1f; float zfar = 100.0f; XMMATRIX m; CPUTOSServices *pServices = CPUTOSServices::GetOSServices(); pServices->GetClientDimensions( &windowWidth, &windowHeight ); m = XMMatrixOrthographicOffCenterLH(0, (float)windowWidth, (float)windowHeight, 0, znear, zfar); ConstantBufferMatrices.Projection = XMMatrixTranspose( m ); // set the vertex shader pImmediateContext->VSSetShader( pVertexShader, NULL, 0 ); UINT VertexStride = sizeof(CPUTGUIVertex); UINT VertexOffset = 0; pImmediateContext->IASetVertexBuffers( 0, 1, &mpUberBuffer, &VertexStride, &VertexOffset ); m = XMMatrixIdentity(); ConstantBufferMatrices.Model = XMMatrixTranspose( m ); pImmediateContext->UpdateSubresource( mpConstantBufferVS, 0, NULL, &ConstantBufferMatrices, 0, 0 ); pImmediateContext->VSSetConstantBuffers( 0, 1, &mpConstantBufferVS ); // -- draw the normal controls -- // draw the control graphics pImmediateContext->PSSetShader( pPixelShader, NULL, 0 ); pImmediateContext->PSSetShaderResources( 0, 1, &mpControlTextureAtlasView ); pImmediateContext->Draw(mUberBufferIndex,0); // draw the control's text pImmediateContext->PSSetShaderResources( 0, 1, &mpTextTextureAtlasView ); pImmediateContext->IASetVertexBuffers( 0, 1, &mpTextUberBuffer, &VertexStride, &VertexOffset ); // draw the text uber-buffer pImmediateContext->Draw(mTextUberBufferIndex,0); // draw the FPS counter if(mbDrawFPS) { pImmediateContext->IASetVertexBuffers( 0, 1, &mpFPSDirectXBuffer, &VertexStride, &VertexOffset ); pImmediateContext->Draw(mFPSBufferIndex, 0); } // -- draw the focused control -- // Draw the focused control's graphics pImmediateContext->PSSetShader( pPixelShader, NULL, 0 ); pImmediateContext->PSSetShaderResources( 0, 1, &mpControlTextureAtlasView ); pImmediateContext->IASetVertexBuffers( 0, 1, &mpFocusedControlBuffer, &VertexStride, &VertexOffset ); // draw the uber-buffer pImmediateContext->Draw(mFocusedControlBufferIndex,0); // Draw the focused control's text pImmediateContext->PSSetShaderResources( 0, 1, &mpTextTextureAtlasView ); pImmediateContext->IASetVertexBuffers( 0, 1, &mpFocusedControlTextBuffer, &VertexStride, &VertexOffset ); // draw the text uber-buffer pImmediateContext->Draw(mFocusedControlTextBufferIndex,0); // restore the drawing state ClearGUIDrawingState(pImmediateContext); HEAPCHECK; }
void Camera::SetLensOrtho(float l, float r, float b, float t, float zn, float zf) { XMMATRIX P = XMMatrixOrthographicOffCenterLH(l, r, b, t, zn, zf); XMStoreFloat4x4(&mProj, P); }
bool SpriteGame::loadContent() { CComPtr<ID3DBlob> compiledShader(compileShader("SpriteShader.fx", "VS_Main", "vs_4_0")); if(compiledShader == nullptr) return false; HRESULT result = device->CreateVertexShader(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), nullptr, &vertexShader); if(FAILED(result)) return false; D3D11_INPUT_ELEMENT_DESC vertexProperties[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXEL", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; result = device->CreateInputLayout(vertexProperties, 2, compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), &inputLayout); if(FAILED(result)) return false; compiledShader = compileShader("SpriteShader.fx", "PS_Main", "ps_4_0"); if(compiledShader == nullptr) return false; result = device->CreatePixelShader(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), nullptr, &pixelShader); if(FAILED(result)) return false; result = D3DX11CreateShaderResourceViewFromFile(device, "Resources/Sprite.dds", nullptr, nullptr, &texture, nullptr); if(FAILED(result)) return false; D3D11_SAMPLER_DESC samplerDescriptor; ZeroMemory(&samplerDescriptor, sizeof(samplerDescriptor)); samplerDescriptor.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDescriptor.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDescriptor.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDescriptor.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDescriptor.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDescriptor.MaxLOD = D3D11_FLOAT32_MAX; result = device->CreateSamplerState(&samplerDescriptor, &textureSampler); if(FAILED(result)) return false; CComPtr<ID3D11Resource> textureResource; texture->GetResource(&textureResource); D3D11_TEXTURE2D_DESC textureDescriptor; ((ID3D11Texture2D*)(textureResource.p))->GetDesc(&textureDescriptor); float halfWidth = textureDescriptor.Width/2.0f; float halfHeight = textureDescriptor.Height/2.0f; Vertex vertices[] = { { XMFLOAT3(-halfWidth, halfHeight, 1.0f), XMFLOAT2(0.0f, 0.0f) }, { XMFLOAT3( halfWidth, halfHeight, 1.0f), XMFLOAT2(1.0f, 0.0f) }, { XMFLOAT3(-halfWidth, -halfHeight, 1.0f), XMFLOAT2(0.0f, 1.0f) }, { XMFLOAT3( halfWidth, -halfHeight, 1.0f), XMFLOAT2(1.0f, 1.0f) } }; D3D11_BUFFER_DESC bufferDescriptor = {0}; bufferDescriptor.Usage = D3D11_USAGE_DEFAULT; bufferDescriptor.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDescriptor.ByteWidth = sizeof(vertices); D3D11_SUBRESOURCE_DATA vertexData = {0}; vertexData.pSysMem = vertices; result = device->CreateBuffer(&bufferDescriptor, &vertexData, &vertexBuffer); if(FAILED(result)) return false; D3D11_BUFFER_DESC matrixBufferDescriptor = {0}; matrixBufferDescriptor.Usage = D3D11_USAGE_DEFAULT; matrixBufferDescriptor.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDescriptor.ByteWidth = sizeof(XMMATRIX); result = device->CreateBuffer(&matrixBufferDescriptor, nullptr, &mvpMatrixBuffer); if(FAILED(result)) return false; sprites[0].setPosition(100, 300); sprites[1].setPosition(400, 100); vpMatrix = XMMatrixIdentity() * XMMatrixOrthographicOffCenterLH(0.0f, 600.0f, 0.0f, 600.0f, 0.1f, 100.0f); D3D11_BLEND_DESC blendDescriptor = {0}; blendDescriptor.RenderTarget[0].BlendEnable = true; blendDescriptor.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDescriptor.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDescriptor.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendDescriptor.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDescriptor.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; blendDescriptor.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendDescriptor.RenderTarget[0].RenderTargetWriteMask = 0x0F; float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; device->CreateBlendState(&blendDescriptor, &blendState); deviceContext->OMSetBlendState(blendState, blendFactor, 0xFFFFFFFF); return true; }
bool EngineBase::LoadContent() { //load models vector<VertexPos> vertexbuffer; vector<int> indexbuffer; vector<SubSet> subsets; if (!SpriteModel::instance()->load_model("rescs/Smodel.in", vertexbuffer, indexbuffer, subsets)) { MessageBox(0, "error loading models!", 0, 0); return false; } //int direct3d device ID3DBlob* vsBuffer = 0; bool compileResult = CompileD3DShader(L"rescs/TextureMap.fx", "VS_Main", "vs_4_0", &vsBuffer); if (compileResult == false) { MessageBox(0, "Error compiling the vertex shader!", 0, 0); return false; } HRESULT d3dResult; d3dResult = d3dDevice_->CreateVertexShader(vsBuffer->GetBufferPointer(), vsBuffer->GetBufferSize(), 0, &solidColorVS_); if (FAILED(d3dResult)) { MessageBox(0, "Error creating the vertex shader!", 0, 0); if (vsBuffer) vsBuffer->Release(); return false; } D3D11_INPUT_ELEMENT_DESC solidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; int totalLayoutElements = ARRAYSIZE(solidColorLayout); d3dResult = d3dDevice_->CreateInputLayout(solidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer(), vsBuffer->GetBufferSize(), &inputLayout_); vsBuffer->Release(); if (FAILED(d3dResult)) { MessageBox(0, "Error creating the input layout!", 0, 0); return false; } ID3DBlob* psBuffer = 0; compileResult = CompileD3DShader(L"rescs/TextureMap.fx", "PS_Main", "ps_4_0", &psBuffer); if (compileResult == false) { MessageBox(0, "Error compiling pixel shader!", 0, 0); return false; } d3dResult = d3dDevice_->CreatePixelShader(psBuffer->GetBufferPointer(), psBuffer->GetBufferSize(), 0, &solidColorPS_); psBuffer->Release(); if (FAILED(d3dResult)) { MessageBox(0, "Error creating pixel shader!", 0, 0); return false; } d3dResult = CreateDDSTextureFromFile(d3dDevice_, L"rescs/resc.dds", nullptr, &colorMap_); if (FAILED(d3dResult)) { MessageBox(0, "Failed to load the texture image!", 0, 0); return false; } D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory(&colorMapDesc, sizeof(colorMapDesc)); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; d3dResult = d3dDevice_->CreateSamplerState(&colorMapDesc, &colorMapSampler_); if (FAILED(d3dResult)) { MessageBox(0, "Failed to create color map sampler state!", 0, 0); return false; } D3D11_BUFFER_DESC vertexDesc; ZeroMemory(&vertexDesc, sizeof(vertexDesc)); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof(VertexPos) * (int)vertexbuffer.size(); D3D11_SUBRESOURCE_DATA resourceData; ZeroMemory(&resourceData, sizeof(resourceData)); resourceData.pSysMem = &vertexbuffer[0]; d3dResult = d3dDevice_->CreateBuffer(&vertexDesc, &resourceData, &vertexBuffer_); if (FAILED(d3dResult)) { MessageBox(0, "Failed to create vertex buffer!", 0, 0); return false; } vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; vertexDesc.ByteWidth = sizeof(int) * (int)indexbuffer.size(); vertexDesc.CPUAccessFlags = 0; resourceData.pSysMem = &indexbuffer[0]; d3dResult = d3dDevice_->CreateBuffer(&vertexDesc, &resourceData, &indexBuffer_); if (FAILED(d3dResult)) { MessageBox(0, "Failed to create index buffer!", 0, 0); return false; } //create constant buffer D3D11_BUFFER_DESC constDesc; ZeroMemory(&constDesc, sizeof(constDesc)); constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constDesc.ByteWidth = sizeof(XMMATRIX); constDesc.Usage = D3D11_USAGE_DEFAULT; d3dResult = d3dDevice_->CreateBuffer(&constDesc, 0, &mvpCB_); if (FAILED(d3dResult)) { return false; } constDesc.ByteWidth = sizeof(tex_co_trans); d3dResult = d3dDevice_->CreateBuffer(&constDesc, 0, &texTrans_); sets = subsets; XMMATRIX view = XMMatrixIdentity(); XMMATRIX projection = XMMatrixOrthographicOffCenterLH(0.0f, 800.0f, 0.0f, 600.0f, 0.1f, 100.0f); vpMatrix_ = XMMatrixMultiply(view, projection); D3D11_BLEND_DESC blendDesc; ZeroMemory(&blendDesc, sizeof(blendDesc)); blendDesc.RenderTarget[0].BlendEnable = TRUE; blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; d3dDevice_->CreateBlendState(&blendDesc, &alphaBlendState_); d3dContext_->OMSetBlendState(alphaBlendState_, blendFactor, 0xFFFFFFFF); //set states UINT stride = sizeof(VertexPos); UINT offset = 0; d3dContext_->IASetInputLayout(inputLayout_); d3dContext_->IASetVertexBuffers(0, 1, &vertexBuffer_, &stride, &offset); d3dContext_->IASetIndexBuffer(indexBuffer_, DXGI_FORMAT_R32_UINT, 0); d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dContext_->VSSetShader(solidColorVS_, 0, 0); d3dContext_->PSSetShader(solidColorPS_, 0, 0); d3dContext_->PSSetShaderResources(0, 1, &colorMap_); d3dContext_->PSSetSamplers(0, 1, &colorMapSampler_); return true; }
void DXCamera2D::VSetOrthoLHOffCenter(OrthoRect rect, float zNear, float zFar) { m_rect = rect; XMMATRIX P = XMMatrixOrthographicOffCenterLH(rect.left, rect.right, rect.bottom, rect.top, zNear, zFar); XMStoreFloat4x4(&m_projection, XMMatrixTranspose(P)); }
void CascadedShadowMapper::VRender(ISceneGraph* graph) { IRenderer* renderer = CmGetApp()->VGetHumanView()->VGetRenderer(); IDeviceTexture* vn[4]; for(UCHAR i = 0; i < m_cascades + 1; ++i) { vn[i] = NULL; } renderer->VSetTextures(eEffect0, (vn+1), m_cascades); ICamera* playerView = graph->VGetCamera().get(); Frustum cascadeFrusta; Frustum ortographicFrusta; CameraComponent* lcc = GetActorCompnent<CameraComponent>(m_lightActorCamera, CM_CMP_CAMERA); //std::shared_ptr<chimera::CameraComponent> vcc = m_viewActor->GetComponent<chimera::CameraComponent>(chimera::CameraComponent::COMPONENT_ID).lock(); renderer->VPushViewTransform(lcc->GetCamera()->GetView(), lcc->GetCamera()->GetIView(), lcc->GetCamera()->GetEyePos(), lcc->GetCamera()->GetViewDir()); ICamera* lightCamera = lcc->GetCamera().get(); //util::ICamera* viewCamera = vcc->GetCamera().get(); ICamera* viewCamera = playerView; //util::Mat4 viewToLight = util::Mat4::Mul(lightCamera->GetView(), viewCamera->GetIView());//vcc->GetCamera()->GetIView()); float distances[3]; for(UCHAR ci = 0; ci < m_cascades; ++ci) { CascadeSettings& settings = m_pCascadesSettings[ci]; /*util::StaticCamera* staticCam; staticCam = (util::StaticCamera*)(m_cascadeCameraActor[ci]->GetComponent<chimera::CameraComponent>(chimera::CameraComponent::COMPONENT_ID).lock()->GetCamera().get());*/ float farr = settings.end; float nnear = settings.start; cascadeFrusta.CreatePerspective(viewCamera->GetAspect(), viewCamera->GetFoV(), nnear, farr); util::Vec3 vmin(FLT_MAX, FLT_MAX, FLT_MAX); util::Vec3 vmax(FLT_MIN, FLT_MIN, FLT_MIN); util::Vec3 vFrustumPoints[8]; util::Vec3 vecs[8]; for(uint i = 0; i < 8; ++i) { util::Vec3 v = util::Mat4::Transform(viewCamera->GetIView(), cascadeFrusta.GetPoints()[i]); vFrustumPoints[i] = v; util::Vec3 pos = util::Mat4::Transform(lightCamera->GetView(), v); vmax = util::Vec3::Max(vmax, pos); vmin = util::Vec3::Min(vmin, pos); } /*FLOAT bound = (farr - nnear) / 1024.0f; util::Vec3 fmin((INT)vmin.x / bound, (INT)vmin.y / bound, (INT)vmin.y / bound); fmin.Scale(bound); vmin = fmin; util::Vec3 fmax((INT)(vmax.x / bound), (INT)(vmax.y / bound), (INT)(vmax.y / bound)); fmax.Scale(bound); vmax = fmax; */ /*vmax = util::Mat4::Transform(lightCamera->GetIView(), vmax); vmin = util::Mat4::Transform(lightCamera->GetIView(), vmin); */ /*util::Vec3 vDiagonal = vFrustumPoints[tbd::rightUpNear] - vFrustumPoints[tbd::leftDownFar]; FLOAT l = vDiagonal.Length(); vDiagonal.Set(l, l, l); // The offset calculated will pad the ortho projection so that it is always the same size // and big enough to cover the entire cascade interval. util::Vec3 diff = vmax - vmin; util::Vec3 vBoarderOffset = vDiagonal - diff; vBoarderOffset.Scale(0.5f); vBoarderOffset.z = 0; // Add the offsets to the projection. vmax = vmax + vBoarderOffset; vmin = vmin - vBoarderOffset; */ float n = min(-120, vmin.z); //todo float ff = vmax.z; distances[ci] = ff - n; XMMATRIX mat = XMMatrixOrthographicOffCenterLH(vmin.x, vmax.x, vmin.y, vmax.y, n, ff); XMStoreFloat4x4(&settings.m_projection.m_m, mat); /* util::StaticCamera staticCam(1,1,1,1); #ifdef CSM_DEBUG staticCam.SetOrthographicProjectionOffCenter(vmin.x, vmax.x, vmin.y, vmax.y, n, ff); staticCam.SetView(lightCamera->GetView(), lightCamera->GetIView()); ortographicFrusta = staticCam.GetFrustum(); #endif*/ ortographicFrusta.CreateOrthographicOffCenter(vmin.x, vmax.x, vmin.y, vmax.y, n, ff); ortographicFrusta.Transform(lightCamera->GetIView()); renderer->VPushProjectionTransform(settings.m_projection, ff - n, 1); m_ppTargets[ci]->VClear(); m_ppTargets[ci]->VBind(); graph->VPushFrustum(&ortographicFrusta); m_pProgram->VBind(); graph->VOnRender(CM_RENDERPATH_SHADOWMAP); m_pProgramInstanced->VBind(); graph->VOnRender(CM_RENDERPATH_SHADOWMAP_INSTANCED); /*m_pProgramInstanced->VBind(); graph->VOnRender(eRenderPath_DrawToShadowMapInstanced);*/ graph->VPopFrustum(); renderer->VPopProjectionTransform(); m_ppBlurChain[ci]->VProcess(); // d3d::GetContext()->GenerateMips(m_ppBlurredTargets[ci]->GetShaderRessourceView()); } renderer->VPopViewTransform(); CmGetApp()->VGetHumanView()->VGetRenderer()->VGetCurrentRenderTarget()->VBind(); IDeviceTexture* v[3]; for(UCHAR i = 0; i < m_cascades; ++i) { v[i] = m_ppBlurredTargets[i]->VGetTexture(); } renderer->VSetTextures(eEffect0, v, m_cascades); //ID3D11ShaderResourceView* debugView = m_ppBlurredTargets[0]->GetShaderRessourceView(); //d3d::GetContext()->PSSetShaderResources(d3d::eEffect3, 1, &debugView); //debugging samplers util::Mat4 mats[3]; //TODO //FLOAT distances[3]; for(UCHAR i = 0; i < m_cascades; ++i) { mats[i] = m_pCascadesSettings[i].m_projection; } IConstShaderBuffer* lb = renderer->VGetConstShaderBuffer(eEnvLightingBuffer); _LightingBuffer* _lb = (_LightingBuffer*)lb->VMap(); _lb->m_view = lightCamera->GetView().m_m; _lb->m_iView = lightCamera->GetIView().m_m; _lb->m_projection[0] = mats[0].m_m; _lb->m_projection[1] = mats[1].m_m; _lb->m_projection[2] = mats[2].m_m; _lb->m_lightPos.x = lcc->GetCamera()->GetEyePos().x; _lb->m_lightPos.y = lcc->GetCamera()->GetEyePos().y; _lb->m_lightPos.z = lcc->GetCamera()->GetEyePos().z; _lb->m_intensity.x = m_intensity.x; _lb->m_intensity.y = m_intensity.y; _lb->m_intensity.z = m_intensity.z; _lb->m_ambient.x = m_ambient.x; _lb->m_ambient.y = m_ambient.y; _lb->m_ambient.z = m_ambient.z; _lb->m_distances.x = distances[0]; _lb->m_distances.y = distances[1]; _lb->m_distances.z = distances[2]; lb->VUnmap(); // renderer->SetCSMSettings(lightCamera->GetView(), lightCamera->GetIView(), mats, lcc->GetCamera()->GetEyePos(), distances); }