Пример #1
0
void Sample::Internal(ID3D11ShaderResourceView * src,ID3D11RenderTargetView * dst)
{
	ID3D11DeviceContext * context;
	device->GetImmediateContext(&context);

	ps.Get()->Bind();

	context->OMSetRenderTargets(1,&dst,nullptr);
	Color c = Color::White();
	context->ClearRenderTargetView(dst,(float*)&c);
	

	context->PSSetShaderResources(0,1,&src);
	FullScreenQuad::BindVS();

	FullScreenQuad::Draw();

	FullScreenQuad::UnbindVS();

	ID3D11RenderTargetView * rtvNull = nullptr;
	ID3D11ShaderResourceView * srvNull = nullptr;

	context->OMSetRenderTargets(1,&rtvNull,nullptr);
	context->PSSetShaderResources(0,1,&srvNull);
}
static void DoRendering (const float* worldMatrix, const float* identityMatrix, float* projectionMatrix, const MyVertex* verts)
{
    // Does actual rendering of a simple triangle

    #if SUPPORT_D3D11
    // D3D11 case
    if (s_DeviceType == kUnityGfxRendererD3D11 && EnsureD3D11ResourcesAreCreated())
    {
        ID3D11DeviceContext* ctx = NULL;
        g_D3D11Device->GetImmediateContext (&ctx);

        ID3D11RenderTargetView*  pCurrentRenderTarget;
        ID3D11DepthStencilView*  pCurrentDepthStencil;

        // Get the current render targets
        ctx->OMGetRenderTargets(1, &pCurrentRenderTarget, &pCurrentDepthStencil);

        ctx->OMSetRenderTargets(1, &g_pD3D11RenderTargetView, nullptr);

        /*
        // update native texture from code
        D3D11_TEXTURE2D_DESC desc;
        g_TexturePointer->GetDesc(&desc);
        unsigned char* data = new unsigned char[desc.Width*desc.Height * 4];
        FillTextureFromCode(desc.Width, desc.Height, desc.Width * 4, data);
        ctx->UpdateSubresource(g_TexturePointer, 0, NULL, data, desc.Width * 4, 0);
        delete[] data;
        */
        const float CLEAR_CLR[4] = { 1, 1, 0, 1 };  // Yellow

        ctx->ClearRenderTargetView(g_pD3D11RenderTargetView, CLEAR_CLR);

        // Restore the original render target
        ctx->OMSetRenderTargets(1, &pCurrentRenderTarget, pCurrentDepthStencil);

        // update constant buffer - just the world matrix in our case
        ctx->UpdateSubresource (g_D3D11CB, 0, NULL, worldMatrix, 64, 0);

        // set shaders
        ctx->VSSetConstantBuffers (0, 1, &g_D3D11CB);
        ctx->VSSetShader (g_D3D11VertexShader, NULL, 0);
        ctx->PSSetShader (g_D3D11PixelShader, NULL, 0);

        // update vertex buffer
        ctx->UpdateSubresource (g_D3D11VB, 0, NULL, verts, sizeof(verts[0])*3, 0);

        // set input assembler data and draw
        ctx->IASetInputLayout (g_D3D11InputLayout);
        ctx->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
        UINT stride = sizeof(MyVertex);
        UINT offset = 0;
        ctx->IASetVertexBuffers (0, 1, &g_D3D11VB, &stride, &offset);
        ctx->Draw (3, 0);

        ctx->Release();
    }
    #endif
}
Пример #3
0
void MSAAFilter::RenderAA()
{
    PIXEvent pixEvent(L"MSAA Resolve + Temporal AA");
    ProfileBlock profileBlock(L"MSAA Resolve + Temporal AA");

    ID3D11DeviceContext* context = deviceManager.ImmediateContext();

    ID3D11RenderTargetView* rtvs[1] = { resolveTarget.RTView };

    context->OMSetRenderTargets(1, rtvs, nullptr);

    if(AppSettings::UseStandardResolve)
    {
        if(AppSettings::MSAAMode == 0)
            context->CopyResource(resolveTarget.Texture, colorTarget.Texture);
        else
            context->ResolveSubresource(resolveTarget.Texture, 0, colorTarget.Texture, 0, colorTarget.Format);
        return;
    }

    const uint32 SampleRadius = static_cast<uint32>((AppSettings::ResolveFilterDiameter / 2.0f) + 0.499f);
    ID3D11PixelShader* pixelShader = resolvePS[AppSettings::MSAAMode];
    context->PSSetShader(pixelShader, nullptr, 0);
    context->VSSetShader(resolveVS, nullptr, 0);

    resolveConstants.Data.TextureSize = Float2(static_cast<float>(colorTarget.Width), static_cast<float>(colorTarget.Height));
    resolveConstants.Data.SampleRadius = SampleRadius;;
    resolveConstants.ApplyChanges(context);
    resolveConstants.SetPS(context, 0);

    ID3D11ShaderResourceView* srvs[] = { colorTarget.SRView, velocityTarget.SRView, depthBuffer.SRView, prevFrameTarget.SRView};
    context->PSSetShaderResources(0, ArraySize_(srvs), srvs);

    ID3D11SamplerState* samplers[] = { samplerStates.LinearClamp(), samplerStates.Point() };
    context->PSSetSamplers(0, ArraySize_(samplers), samplers);

    ID3D11Buffer* vbs[1] = { nullptr };
    UINT strides[1] = { 0 };
    UINT offsets[1] = { 0 };
    context->IASetVertexBuffers(0, 1, vbs, strides, offsets);
    context->IASetInputLayout(nullptr);
    context->IASetIndexBuffer(nullptr, DXGI_FORMAT_R16_UINT, 0);
    context->Draw(3, 0);

    rtvs[0] = nullptr;
    context->OMSetRenderTargets(1, rtvs, nullptr);

    srvs[0] = srvs[1] = srvs[2] = nullptr;
    context->PSSetShaderResources(0, 3, srvs);

    context->CopyResource(prevFrameTarget.Texture, resolveTarget.Texture);
}
Пример #4
0
void SwapChain::Present(ID3D11DeviceContext& deviceContext)
{
    ID3D11RenderTargetView* tmpRenderTargetView = backBuffer_.get();
    deviceContext.OMSetRenderTargets(1, &tmpRenderTargetView, depthStencilView_.get());

    e_throw_com_ret_error(dxgiSwapChain_->Present(0, 0), "IDXGISwapChain::Present");    
}
void App::RenderTerrain2( bool bReset, float fTime, float fElapsedTime )
{
	g_ResetTerrain = bReset;

	if (g_ResetTerrain)
	{
		g_ResetTerrain = false;

		DeformInitTerrain(context);
	}

	renderer->changeToMainFramebuffer();	

	ID3D11DeviceContext* pContext =  GetApp()->GetContext();

	ID3D11RenderTargetView* pBackBufferRTV; 
	ID3D11DepthStencilView* pBackBufferDSV;

	pContext->OMGetRenderTargets(1, &pBackBufferRTV, &pBackBufferDSV);

	// Clear render target and the depth stencil 
	float ClearColor[4] = { 1.0f, 0.0f, 1.0f, 1.0f };					// Purple to better spot terrain cracks (disable sky cube).
	//float ClearColor[4] = { 0.465f, 0.725f, 0.0f, 1.0f };				// NV green for colour-consistent illustrations.
	pContext->ClearRenderTargetView(pBackBufferRTV, ClearColor);					
	pContext->ClearDepthStencilView(pBackBufferDSV, D3D11_CLEAR_DEPTH, 1.0, 0);	//  ¸®»çÀÌ¡½Ã Error!
	pContext->OMSetRenderTargets(1, &pBackBufferRTV, pBackBufferDSV);
	RenderToBackBuffer(renderer, fTime, fElapsedTime, NULL);

	
}
Пример #6
0
void App::RenderText(const std::wstring& text, Float2 pos)
{
    ID3D11DeviceContext* context = deviceManager.ImmediateContext();

    // Set the backbuffer and viewport
    ID3D11RenderTargetView* rtvs[1] = { deviceManager.BackBuffer() };
    context->OMSetRenderTargets(1, rtvs, NULL);

    float clearColor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
    context->ClearRenderTargetView(rtvs[0], clearColor);

    SetViewport(context, deviceManager.BackBufferWidth(), deviceManager.BackBufferHeight());

    // Draw the text
    Float4x4 transform;
    transform.SetTranslation(Float3(pos.x, pos.y,0.0f));
    spriteRenderer.Begin(context, SpriteRenderer::Point);
    spriteRenderer.RenderText(font, text.c_str(), transform.ToSIMD());
    spriteRenderer.End();

    // Present
    deviceManager.SwapChain()->Present(0, 0);

    // Pump the message loop
    window.MessageLoop();
}
Пример #7
0
void RenderTargetPingPong::Apply(ID3D11Device* device, ID3DX11EffectTechnique* technique)
{
	ID3D11DeviceContext* context;
	device->GetImmediateContext(&context);
	
	ID3D11Buffer* zero = 0;
	UINT nought = 0;
	context->IASetVertexBuffers(0,1,&zero,&nought,&nought);
	context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
	context->IASetInputLayout(0);

	{
		ID3D11RenderTargetView* view[] = { m_target->RenderTargetView() };
		context->OMSetRenderTargets(1, const_cast<ID3D11RenderTargetView**> (view), m_depth_stencil_view);
	}

	m_shader_resource_variable->SetResource(m_source->ShaderResourceView());

	for(UINT n = 0; n < Effect::NumPasses(technique); ++n)
	{
		technique->GetPassByIndex(n)->Apply(0,context);
		context->Draw(4,0);
	}

	m_shader_resource_variable->SetResource(0);
	m_last_target = m_target;
	std::swap(m_source,m_target);
}
Пример #8
0
void FForwardPlusRenderer::DoDepthNormalPrePass(const FCamera& Camera, class IScene* Scene)
{
	// Clear depth buffer
	ID3D11DeviceContext* DeviceContext = GraphicsContext->GetImmediateContext();

	const FLOAT NormalsClearColour[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
	const FLOAT DepthClearColour[4] = { 1.0f, 1.0f, 1.0f, 1.0f };

	ID3D11RenderTargetView* Targets[2] = { NormalTarget->GetRenderTarget(), DepthTarget->GetRenderTarget() };
	DeviceContext->ClearDepthStencilView(GraphicsContext->GetDepthStencil(), D3D11_CLEAR_STENCIL | D3D11_CLEAR_DEPTH, 1.0f, 0);

	DeviceContext->ClearRenderTargetView(NormalTarget->GetRenderTarget(), NormalsClearColour);
	DeviceContext->ClearRenderTargetView(DepthTarget->GetRenderTarget(), DepthClearColour);

	DeviceContext->OMSetRenderTargets(2, Targets, GraphicsContext->GetDepthStencil());

	FViewport Fullscreen(0, 0, GraphicsContext->GetWidth(), GraphicsContext->GetHeight());
	D3D11_VIEWPORT Viewport = Fullscreen.CreateRenderViewport();
	DeviceContext->RSSetViewports(1, &Viewport);

	InstanceBuffer->SetWorld(glm::mat4(1.0));
	FDrawCall Params(DeviceContext, InstanceBuffer.Get());
	Params.OverrideMaterial = std::bind(&FForwardPlusRenderer::OverrideMaterialDepthNormalPass, this, std::placeholders::_1);
	Scene->Draw(Params);
}
Пример #9
0
void FForwardPlusRenderer::DoScenePass(const FCamera& Camera, class IScene* Scene)
{
	// Clear depth buffer
	ID3D11DeviceContext* DeviceContext = GraphicsContext->GetImmediateContext();

	const FLOAT ClearColour[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
	ID3D11RenderTargetView* BackBuffer = HighDynamicRangeMSAATarget->GetRenderTarget();
	DeviceContext->ClearDepthStencilView(HighDynamicRangeMSAATarget->GetDepthStencil(), D3D11_CLEAR_STENCIL | D3D11_CLEAR_DEPTH, 1.0f, 0);
	DeviceContext->ClearRenderTargetView(BackBuffer, ClearColour);

	DeviceContext->OMSetRenderTargets(1, &BackBuffer, HighDynamicRangeMSAATarget->GetDepthStencil());

	FViewport Fullscreen(0, 0, GraphicsContext->GetWidth(), GraphicsContext->GetHeight());
	D3D11_VIEWPORT Viewport = Fullscreen.CreateRenderViewport();
	DeviceContext->RSSetViewports(1, &Viewport);

	InstanceBuffer->SetWorld(glm::mat4(1.0));

	ID3D11RasterizerState* PreviousState = nullptr;

	if (ForceWireframe.AsBoolean())
	{
		DeviceContext->RSGetState(&PreviousState);
		DeviceContext->RSSetState(GraphicsContext->GetRenderStates()->WireframeRasterizer);
	}

	FDrawCall Params(DeviceContext, InstanceBuffer.Get());
	Scene->Draw(Params);

	if (PreviousState != nullptr)
	{
		DeviceContext->RSSetState(PreviousState);
	}
}
Пример #10
0
void RDX11RenderTargetMgr::ClearAndSetMaineFrame()
{
	ID3D11DeviceContext* pContext = GLOBAL::D3DContext();

	pContext->OMSetRenderTargets( 1, &pMainFrameRTV, pDSV );
	pContext->ClearRenderTargetView( pMainFrameRTV, clearColor);
	pContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0, 0 );
}
void ParticleSystemEffectBinder::UnbindOM()
{
	ID3D11DeviceContext * context = GetContext();

	ID3D11RenderTargetView * rtvs[2] = {nullptr,nullptr};

	context->OMSetRenderTargets(2,rtvs,nullptr);
}
Пример #12
0
    void graphics_extensions::BindRenderTargets(Texture** buffersBegin, Texture** buffersEnd, Texture* depthStencilBuffer) {
        ID3D11DeviceContext* context = GraphicsManager::Get()->GetImmidiateContext();

        ID3D11RenderTargetView* rtViews[4] = { nullptr, nullptr, nullptr, nullptr };
        I32 buffersCount = buffersEnd - buffersBegin;
        _ASSERT(buffersCount > 0 && buffersCount < _countof(rtViews));

        U32 i = 0;
        for(Texture** it = buffersBegin; it < buffersEnd; ++it) {
            rtViews[i++] = (*it)->GetRTView();
        }

        if (depthStencilBuffer) {
            context->OMSetRenderTargets(buffersCount, rtViews, depthStencilBuffer->GetDSView());
        } else {
            context->OMSetRenderTargets(buffersCount, rtViews, nullptr);
        }
        
    }
Пример #13
0
//-----------------------------------------------
void CPUTRenderTargetColor::SetRenderTarget(
    CPUTRenderParameters   &renderParams,
    CPUTRenderTargetDepth  *pDepthBuffer,
    DWORD                   renderTargetIndex,
    const float            *pClearColor,
    bool                    clear,
    float                   zClearVal
)
{
    // ****************************
    // Save the current render target "state" so we can restore it later.
    // ****************************
    mSavedWidth   = CPUTRenderTargetColor::sCurrentWidth;
    mSavedHeight  = CPUTRenderTargetColor::sCurrentHeight;

    // Save the render target view so we can restore it later.
    mpSavedColorRenderTargetView = CPUTRenderTargetColor::GetActiveRenderTargetView();
    mpSavedDepthStencilView      = CPUTRenderTargetDepth::GetActiveDepthStencilView();

    CPUTRenderTargetColor::SetActiveWidthHeight( mWidth, mHeight );
    CPUTRenderTargetDepth::SetActiveWidthHeight( mWidth, mHeight );

    // TODO: support multiple render target views (i.e., MRT)
    ID3D11DeviceContext *pContext = CPUT_DX11::GetContext();

    // Clear the shader resources to avoid a hazard warning
    ID3D11ShaderResourceView *pNullResources[16] = {0};
    pContext->PSSetShaderResources(0, 16, pNullResources );
    pContext->VSSetShaderResources(0, 16, pNullResources );

    // ****************************
    // Set the new render target states
    // ****************************
    ID3D11DepthStencilView *pDepthStencilView = pDepthBuffer ? pDepthBuffer->GetDepthBufferView() : NULL;
    pContext->OMSetRenderTargets( 1, &mpColorRenderTargetView, pDepthStencilView );

    CPUTRenderTargetColor::SetActiveRenderTargetView(mpColorRenderTargetView);
    CPUTRenderTargetDepth::SetActiveDepthStencilView(pDepthStencilView);

    if( clear )
    {
        pContext->ClearRenderTargetView( mpColorRenderTargetView, pClearColor );
        if( pDepthStencilView )
        {
            pContext->ClearDepthStencilView( pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, zClearVal, 0 );
        }
    }
    D3D11_VIEWPORT viewport  = { 0.0f, 0.0f, (float)mWidth, (float)mHeight, 0.0f, 1.0f };
    pContext->RSSetViewports(1, &viewport);

    mRenderTargetSet = true;
	mSoftwareTextureDirty = true;

} // CPUTRenderTargetColor::SetRenderTarget()
Пример #14
0
    void graphics_extensions::UnbindAll() {
        ID3D11DeviceContext* context = GraphicsManager::Get()->GetImmidiateContext();

        ID3D11RenderTargetView* rtViews[4];
        memset(rtViews, 0, sizeof(ID3D11RenderTargetView*) * _countof(rtViews));
        context->OMSetRenderTargets(_countof(rtViews), rtViews, nullptr);

        ID3D11ShaderResourceView* srViews[6];
        memset(srViews, 0, sizeof(ID3D11ShaderResourceView*) * _countof(srViews));
        context->PSSetShaderResources(0, _countof(srViews), srViews);
    }
Пример #15
0
//---------------------------------------------------------------------------
void ShadowMapGen::End()
{
    ID3D11DeviceContext* dc = m_rc->Context();

    // Restore the render targets
    ID3D11RenderTargetView* rt  = m_pSurface->GetRenderTargetView();
    ID3D11DepthStencilView* dsv = m_pSurface->GetDepthStencilView();
    dc->OMSetRenderTargets(1, &rt, dsv);    
    dc->RSSetViewports( 1, &m_pSurface->GetViewPort() );
    
    m_rc = NULL;
}
Пример #16
0
// |----------------------------------------------------------------------------|
// |						   SetAsRenderTarget								|
// |----------------------------------------------------------------------------|
void Texture::SetAsRenderTarget()
{
    ID3D11DeviceContext* deviceContext = D3DManager::GetRef()->GetDeviceContext();
    ID3D11DepthStencilView* depthStencilView = D3DManager::GetRef()->GetDepthStencilView();

	// Bind the render target view and depth stencil buffer to the output render pipeline.
	deviceContext->OMSetRenderTargets(1, &m_renderTargetView, depthStencilView);
	
	// Set the viewport.
    deviceContext->RSSetViewports(1, &m_viewport);
	
	return;
}
void ParticleSystemEffectBinder::BindOM()
{
	ID3D11DeviceContext * context = GetContext();

	ID3D11RenderTargetView * rtvs[2] = {rtvColor,rtvLinearDepth.Get()->GetRenderTargetPtr()};
	float color[4] = {0.0f,0.0f,0.0f,0.0f};
	context->ClearRenderTargetView(rtvColor,color);
	float depth[4] = {1.0f,0.0f,0.0f,0.0f};

	context->ClearRenderTargetView(rtvLinearDepth.Get()->GetRenderTargetPtr(),depth);

	context->OMSetRenderTargets(2,rtvs,nullptr);
}
Пример #18
0
void ToneMapper::IntRun(ID3D11ShaderResourceView * src,ID3D11RenderTargetView * dst)
{
	ID3D11DeviceContext * context;
	device->GetImmediateContext(&context);

	ID3D11ShaderResourceView * srvNull[2] = {nullptr,nullptr};
	ID3D11RenderTargetView * rtvNull = nullptr;

	shader.Get()->Bind();
	FullScreenQuad::BindVS();

	ID3D11ShaderResourceView * srcSrv[2] = {src,bloomTexture.Get()->GetShaderResourcePointer()};


	context->PSSetShaderResources(0,2,srcSrv);
	context->OMSetRenderTargets(1,&dst,nullptr);

	FullScreenQuad::Draw();

	context->PSSetShaderResources(0,2,srvNull);
	context->OMSetRenderTargets(1,&rtvNull,nullptr);

}
Пример #19
0
//-----------------------------------------------
void CPUTRenderTargetDepth::SetRenderTarget(
    CPUTRenderParameters   &renderParams,
    DWORD                   renderTargetIndex,
    float                   zClearVal,
    bool                    clear
)
{
    // ****************************
    // Save the current render target "state" so we can restore it later.
    // ****************************
    mSavedWidth   = CPUTRenderTargetDepth::GetActiveWidth();
    mSavedHeight  = CPUTRenderTargetDepth::GetActiveHeight();

    CPUTRenderTargetColor::SetActiveWidthHeight( mWidth, mHeight );
    CPUTRenderTargetDepth::SetActiveWidthHeight( mWidth, mHeight );

    // TODO: support multiple render target views (i.e., MRT)
    ID3D11DeviceContext *pContext = CPUT_DX11::GetContext();

    // Make sure this render target isn't currently bound as a texture.
    static ID3D11ShaderResourceView *pSRV[16] = {0};
    pContext->PSSetShaderResources( 0, 16, pSRV );

    // Save the color and depth views so we can restore them later.
    mpSavedColorRenderTargetView = CPUTRenderTargetColor::GetActiveRenderTargetView();
    mpSavedDepthStencilView      = CPUTRenderTargetDepth::GetActiveDepthStencilView();

    // Clear the shader resources to avoid a hazard warning
    ID3D11ShaderResourceView *pNullResources[16] = {0};
    pContext->PSSetShaderResources(0, 16, pNullResources );
    pContext->VSSetShaderResources(0, 16, pNullResources );

    // ****************************
    // Set the new render target states
    // ****************************
    ID3D11RenderTargetView *pView[1] = {NULL};
    pContext->OMSetRenderTargets( 1, pView, mpDepthStencilView );

    CPUTRenderTargetColor::SetActiveRenderTargetView( NULL );
    CPUTRenderTargetDepth::SetActiveDepthStencilView( mpDepthStencilView );

    if( clear )
    {
        pContext->ClearDepthStencilView( mpDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, zClearVal, 0 );
    }
    D3D11_VIEWPORT viewport  = { 0.0f, 0.0f, (float)mWidth, (float)mHeight, 0.0f, 1.0f };
    pContext->RSSetViewports( 1, &viewport );

    mRenderTargetSet = true;
} // CPUTRenderTargetDepth::SetRenderTarget()
bool ClearRenderingRoutine::Render(float deltaTime)
{
	ID3D11DeviceContext* context = m_Renderer->GetImmediateContext();
	
	// Set rt to back buffer
	ID3D11RenderTargetView* bbufferRTV = m_Renderer->GetBackBufferView();
	context->OMSetRenderTargets(1, &bbufferRTV, m_Renderer->GetBackDepthStencilView());

	// Clear the back buffer 
    float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f };
	context->ClearRenderTargetView(m_Renderer->GetBackBufferView(), ClearColor);
	context->ClearDepthStencilView(m_Renderer->GetBackDepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0);

	return true;
}
Пример #21
0
///////////////////////////////////////////////////////////////////////////////////////////////////
/// IvyApp::DrawUI
///
/// @brief
///     
/// @return
///     N/A
///////////////////////////////////////////////////////////////////////////////////////////////////
void IvyApp::DrawUI()
{
    ID3D11DeviceContext* pContext = m_pDxData->pD3D11Context;
    ID3D11Device* pDevice = m_pDxData->pD3D11Device;

    UINT acquireKey = 1;
    UINT releaseKey = 0;
    UINT timeout = 5;

    HRESULT hr = m_pUIData->pUserInterfaceMutexD3D->AcquireSync(acquireKey, timeout);

    FLOAT blendFactors[4];
    UINT sampleMask = 0xFFFFFFFF;

    ID3D11BlendState* pLastBlendState = NULL;
    pContext->OMGetBlendState(&pLastBlendState, blendFactors, &sampleMask);

    if (hr == WAIT_OBJECT_0)
    {
        pContext->OMSetRenderTargets(1, &m_pDxData->pAppRenderTargetView, NULL);

        CameraBufferData* pCameraData = reinterpret_cast<CameraBufferData*>(m_pUIData->pUserInterfaceCameraBuf->Map(m_pDxData->pD3D11Context));
        pCameraData->worldMatrix = XMMatrixRotationX(-3.14f/2.0f) * XMMatrixScaling(2, 2, 1);
        pCameraData->viewMatrix = XMMatrixTranslation(0, 0, 2.0f) * m_pCamera->W2C();
        pCameraData->projectionMatrix = m_pCamera->C2S();

        m_pUIData->pUserInterfaceCameraBuf->Unmap(pContext);

        m_pUIData->pUserInterfaceVS->Bind(pContext);
        m_pUIData->pUserInterfaceCameraBuf->BindVS(pContext, 0);

        m_pDxData->pD3D11Context->PSSetShaderResources(0, 1, &m_pUIData->pUserInterfaceSRV);
        m_pUIData->pUserInterfacePS->Bind(pContext);

        m_pDxData->pD3D11Context->OMSetBlendState(m_pUIData->pUserInterfaceBlendState, blendFactors, sampleMask);

        m_pUIData->pUserInterfaceQuad->Bind(m_pDxData->pD3D11Context);
        m_pUIData->pUserInterfaceQuad->Draw(m_pDxData->pD3D11Context);
    }

    hr = m_pUIData->pUserInterfaceMutexD3D->ReleaseSync(releaseKey);

    m_pDxData->pD3D11Context->OMSetBlendState(pLastBlendState, blendFactors, sampleMask);

}
Пример #22
0
HRESULT DxAssist::SetRenderTarget(DxRTDevice* RTDevice, uint w, uint h)
{
    HRESULT hresult = E_FAIL;

    ID3D11Device* device = m_device;
    ID3D11DeviceContext* deviceContext = m_deviceContext;

    ID3D11RenderTargetView*  poldRT = 0;
    ID3D11DepthStencilView*  poldDS = 0;
    D3D11_VIEWPORT vp;
    const float clear[] = { 0, 0, 0, 90/255.0f}; //red,green,blue,alpha

    ASSERT(device);
    ASSERT(deviceContext);

    KGLOG_PROCESS_ERROR(RTDevice);
    KGLOG_PROCESS_ERROR(RTDevice->RTView);
    KGLOG_PROCESS_ERROR(RTDevice->RTDepthStencil);
    KGLOG_PROCESS_ERROR(RTDevice->RTDepthStencilBuf);

    deviceContext->OMGetRenderTargets(1, &poldRT, &poldDS );
    deviceContext->OMSetRenderTargets(1, &RTDevice->RTView, RTDevice->RTDepthStencil);

    vp.TopLeftX = 0;
    vp.TopLeftY = 0;
    vp.Width    = (float)w;
    vp.Height   = (float)h;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    deviceContext->RSSetViewports(1, &vp);
    
    deviceContext->ClearRenderTargetView(RTDevice->RTView, clear);
    deviceContext->ClearDepthStencilView(RTDevice->RTDepthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

    {
        RTSaveInfo info;
        info.RTView = poldRT;
        info.RTStencil = poldDS;
        s_RTSaveInfoStack.push(info);
    }
    hresult = S_OK;
Exit0:
    return hresult;
}
Пример #23
0
void Draw()
{
	ID3D11DeviceContext* context = g_d3d.context_.get();
	
	// Clear
	float clearColor[] = { 0.3f, 0.3f, 0.3f, 1.0f };
	context->ClearRenderTargetView( g_d3d.backBufferRTV_.get(), clearColor );

	auto* rtv = g_d3d.backBufferRTV_.get();
	context->OMSetRenderTargets( 1, &rtv, nullptr );
	
	// Draw body

	auto cbModelWVP = DirectX::XMMatrixIdentity();
	auto matWorld = DirectX::XMMatrixIdentity();
	matWorld = DirectX::XMMatrixRotationRollPitchYaw( g_d3d.jointRot_[ 0 ], g_d3d.jointRot_[ 1 ], g_d3d.jointRot_[ 2 ] );
	auto matView =  DirectX::XMMatrixLookAtLH(
		DirectX::XMVectorSet( 0, 0, -3, 0 ), DirectX::XMVectorSet( 0, 0, 5, 0 ), DirectX::XMVectorSet( 0, 1, 0, 0 )
		);
	auto matProj = DirectX::XMMatrixPerspectiveFovLH(
		DirectX::XMConvertToRadians( 50 ), (float)g_windowWidth / (float)g_windowHeight, 0.01f, 1000.0f
		);
	cbModelWVP = matWorld * matView * matProj;
	cbModelWVP = DirectX::XMMatrixTranspose( cbModelWVP );
	g_d3d.context_->UpdateSubresource( g_d3d.modelCB_.get(), 0, nullptr, &cbModelWVP, 0, 0 );

	auto* vb = g_d3d.modelVB_.get();
	unsigned int stride = sizeof( D3D::MeshFormat );
	unsigned int offset = 0;
	auto* cb = g_d3d.modelCB_.get();
	D3D11_VIEWPORT viewport = { 0, 0, g_windowWidth, g_windowHeight, 0, 1 };
	context->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
	context->IASetInputLayout( g_d3d.modelIL_.get() );
	context->IASetVertexBuffers( 0, 1, &vb, &stride, &offset );
	context->VSSetShader( g_d3d.modelVS_.get(), nullptr, 0 );
	context->VSSetConstantBuffers( 0, 1, &cb );
	context->RSSetState( g_d3d.rasterState_.get() );
	context->PSSetShader( g_d3d.modelPS_.get(), nullptr, 0 );
	context->RSSetViewports( 1, &viewport );
	context->Draw( 18, 0 );

	g_d3d.swapChain_->Present( 1, 0 );
}
Пример #24
0
//-----------------------------------------
// TODO: This function is exactly the same as the RestoreRenderTargetColor().
void CPUTRenderTargetDepth::RestoreRenderTarget( CPUTRenderParameters &renderParams )
{
    ASSERT( mRenderTargetSet, "Render target restored without calling SetRenderTarget()");

    ID3D11DeviceContext *pContext = CPUT_DX11::GetContext();

    pContext->OMSetRenderTargets( 1, &mpSavedColorRenderTargetView, mpSavedDepthStencilView );

    CPUTRenderTargetColor::SetActiveWidthHeight( mSavedWidth, mSavedHeight );
    CPUTRenderTargetDepth::SetActiveWidthHeight( mSavedWidth, mSavedHeight );
    CPUTRenderTargetColor::SetActiveRenderTargetView( mpSavedColorRenderTargetView );
    CPUTRenderTargetDepth::SetActiveDepthStencilView( mpSavedDepthStencilView );

    // TODO: save/restore original VIEWPORT settings, not assume full-screen viewport.
    D3D11_VIEWPORT viewport  = { 0.0f, 0.0f, (float)mSavedWidth, (float)mSavedHeight, 0.0f, 1.0f };
    pContext->RSSetViewports( 1, &viewport );

    mRenderTargetSet = false;
} // CPUTRenderTarget::RestoreRenderTarget()
Пример #25
0
void PipelineStateCache::setRenderTargets(uint32 numViews, ID3D11RenderTargetView* const * renderTargetViews, ID3D11DepthStencilView* depthStencilView)
{
  bool hasChanges = false;

  for (uint32 i = 0; i < MAX_RENDER_TARGETS; ++i)
  {
    hasChanges |= renderTargetViews[i] != m_currentlyBoundRTV[i];
    m_currentlyBoundRTV[i] = renderTargetViews[i];
  }

  if (depthStencilView != m_currentlyBoundDSV)
  {
    hasChanges = true;
    m_currentlyBoundDSV = depthStencilView;
  }

  if (hasChanges)
  {
    m_deviceContext->OMSetRenderTargets(numViews, m_currentlyBoundRTV, m_currentlyBoundDSV);
  }
}
Пример #26
0
HRESULT DxAssist::RestoreRenderTarget()
{
    ASSERT(s_RTSaveInfoStack.size() > 0);
    
    HRESULT hr = E_FAIL;
    HRESULT hresult = E_FAIL;
    ID3D11DeviceContext* deviceContext = m_deviceContext;

    KGLOG_PROCESS_ERROR(deviceContext);

    {
        RTSaveInfo info = s_RTSaveInfoStack.top();
        s_RTSaveInfoStack.pop();

        deviceContext->OMSetRenderTargets(1, &info.RTView, info.RTStencil);
        SAFE_RELEASE(info.RTView);
        SAFE_RELEASE(info.RTStencil);
    }

    hresult = S_OK;
Exit0:
    return hresult;
}
void D3D11CanvasWindowGraphics::Render()
{
	RECT clientRc;
	GetClientRect(m_hWnd, &clientRc);
	RectF clientRcf((float)clientRc.left, (float)clientRc.top,
		(float)clientRc.right, (float)clientRc.bottom);
	D2D1_RECT_F clientRectf = D2D1::RectF((FLOAT)clientRc.left, (FLOAT)clientRc.top,
		(FLOAT)clientRc.right, (FLOAT)clientRc.bottom);

	ID3D11DeviceContext* pContext = m_driver->GetD3D11Context();

	// Clear to black
	static const float BG_COLOR[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
	pContext->ClearRenderTargetView(m_backBufferRTV, BG_COLOR);

	// TODO: CLEAN UP THIS MESS!!!

	if (m_image)
	{
		// Set up rasterizer
		RECT clientRc;
		GetClientRect(m_hWnd, &clientRc);
		RectF clientRcf((float)clientRc.left, (float)clientRc.top,
			(float)clientRc.right, (float)clientRc.bottom);
		D3D11_VIEWPORT vp = CD3D11_VIEWPORT(
			clientRcf.left,
			clientRcf.top,
			clientRcf.right - clientRcf.left,
			clientRcf.bottom - clientRcf.top);
		pContext->RSSetViewports(1, &vp);

		// Set up output merger
		ID3D11RenderTargetView* rtv = m_backBufferRTV;
		pContext->OMSetRenderTargets(1, &rtv, NULL);
		pContext->OMSetBlendState(m_driver->GetOverBlend(), NULL, 0xFFFFFFFF);

		D3D11ImagePtr d3d11Image = std::static_pointer_cast<D3D11Image, DriverImage>(
			m_image->GetDriverImage());
		ID3D11ShaderResourceView* srv = d3d11Image->GetSRV();
		ID3D11SamplerState* ss = m_driver->GetBilinearSampler();

		// Set up pixel shader
		pContext->PSSetShader(m_driver->GetTexturedPixelShader(), NULL, 0);
		pContext->PSSetShaderResources(0, 1, &srv);
		pContext->PSSetSamplers(0, 1, &ss);

		m_driver->RenderQuad(m_camera->GetCanvasToClip(clientRcf),
			m_image->GetCanvasRect());

		srv = NULL;
		pContext->PSSetShaderResources(0, 1, &srv);
	}

	// Render something into Direct2D target

	ComPtr<ID2D1RenderTarget> pD2DTarget = m_d2dTarget->AcquireTarget();

	pD2DTarget->BeginDraw();

	// Clear to transparent black
	pD2DTarget->Clear(D2D1::ColorF(D2D1::ColorF::Black, 0.0f));

	// Create brush for drawing stuff
	ID2D1SolidColorBrush* brush;
	pD2DTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Blue), &brush);
	
	Matrix3x2f canvasToViewport = m_camera->GetCanvasToViewport(clientRcf);

	// Draw the extensible image's tile structure
	const ExtensibleImage::TileMap& tiles = m_extensibleImage->GetTileMap();
	for (ExtensibleImage::TileMap::const_iterator it = tiles.begin();
		it != tiles.end(); ++it)
	{
		const RectF& canvasRect = it->second->GetCanvasRect();

		ID2D1Factory* d2dFactory;
		pD2DTarget->GetFactory(&d2dFactory);

		ID2D1RectangleGeometry* rectGeom;
		d2dFactory->CreateRectangleGeometry(
			D2D1::RectF(canvasRect.left, canvasRect.top, canvasRect.right, canvasRect.bottom),
			&rectGeom);

		ID2D1TransformedGeometry* transGeom;
		d2dFactory->CreateTransformedGeometry(rectGeom,
			D2D1::Matrix3x2F(canvasToViewport.m11, canvasToViewport.m12,
			canvasToViewport.m21, canvasToViewport.m22,
			canvasToViewport.m31, canvasToViewport.m32),
			&transGeom);

		rectGeom->Release();

		pD2DTarget->DrawGeometry(transGeom, brush);

		transGeom->Release();

		d2dFactory->Release();
	}

	// Draw some text
	RenderPrintf(pD2DTarget, m_textFormat, clientRectf, brush,
		L"Welcome to Paint Sandbox!");

	brush->Release();

	pD2DTarget->EndDraw();

	m_d2dTarget->ReleaseTarget();

	// Transfer Direct2D target to display
	//m_driver->RenderD2DTarget(m_d2dTarget);

	// Set up rasterizer
	D3D11_VIEWPORT vp = CD3D11_VIEWPORT(
		clientRcf.left,
		clientRcf.top,
		clientRcf.right - clientRcf.left,
		clientRcf.bottom - clientRcf.top);
	pContext->RSSetViewports(1, &vp);

	// Set up output merger
	ID3D11RenderTargetView* rtv = m_backBufferRTV;
	pContext->OMSetRenderTargets(1, &rtv, NULL);
	pContext->OMSetBlendState(m_driver->GetOverBlend(), NULL, 0xFFFFFFFF);

	ID3D11ShaderResourceView* srv = m_d2dTarget->AcquireSRV();
	ID3D11SamplerState* ss = m_driver->GetBilinearSampler();

	// Set up pixel shader
	pContext->PSSetShader(m_driver->GetTexturedPixelShader(), NULL, 0);
	pContext->PSSetShaderResources(0, 1, &srv);
	pContext->PSSetSamplers(0, 1, &ss);

	m_driver->RenderQuad(Matrix3x2f::IDENTITY, RectF(-1.0f, 1.0f, 1.0f, -1.0f));

	srv = NULL;
	pContext->PSSetShaderResources(0, 1, &srv);

	m_d2dTarget->ReleaseSRV();
}
Пример #28
0
// WinMain
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
    HRESULT hr;


    // ウィンドウクラスを登録
    WNDCLASSEX wcex = {
        sizeof( WNDCLASSEX ),			// cbSize
        CS_HREDRAW | CS_VREDRAW,		// style
        WndProc,						// lpfnWndProc
        0,								// cbClsExtra
        0,								// cbWndExtra
        hInstance,						// hInstance
        NULL,							// hIcon
        NULL,							// hCursor
        ( HBRUSH )( COLOR_WINDOW + 1 ),	// hbrBackGround
        NULL,							// lpszMenuName
        g_className,					// lpszClassName
        NULL							// hIconSm
    };
    if ( ! RegisterClassEx( &wcex ) )
    {
        MessageBox( NULL, _T( "失敗: RegisterClassEx()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "RegisterClassEx: ok\n" ) );


    // ウィンドウサイズを計算
    RECT r = { 0, 0, 800, 450 };   // 800x450 (16:9)
    if ( ! AdjustWindowRect( &r, WS_OVERLAPPEDWINDOW, FALSE ) )
    {
        MessageBox( NULL, _T( "失敗: AdjustWindowRect()" ), _T( "エラー" ),  MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "AdjustWindowRect: ok (%d, %d)-(%d, %d)\n" ), r.left, r.top, r.right, r.bottom );


    // ウィンドウ生成
    HWND hWnd;
    hWnd = CreateWindow( g_className,
                         g_windowName,
                         WS_OVERLAPPEDWINDOW,
                         CW_USEDEFAULT,
                         0,
                         r.right - r.left,
                         r.bottom - r.top,
                         NULL,
                         NULL,
                         hInstance,
                         NULL );
    if ( hWnd == NULL )
    {
        MessageBox( NULL, _T( "失敗: CreateWindow()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "CreateWindow: ok\n" ) );


    // ウィンドウ表示
    ShowWindow(hWnd, nCmdShow);
    dtprintf( _T( "ShowWindow: ok\n" ) );



    // スワップチェイン設定
    DXGI_SWAP_CHAIN_DESC scDesc = {
        {
            1280,									// BufferDesc.Width
            720,									// BufferDesc.Height
            {
                60,									// BufferDesc.RefreshRate.Numerator
                1									// BufferDesc.RefreshRate.Denominator
            },
            DXGI_FORMAT_R16G16B16A16_FLOAT,			// BufferDesc.Format
            DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED,	// BufferDesc.ScanlineOrdering
            DXGI_MODE_SCALING_CENTERED				// BufferDesc.Scaling
        },
        {
            1,										// SampleDesc.Count
            0										// SampleDesc.Quality
        },
        DXGI_USAGE_RENDER_TARGET_OUTPUT,			// BufferUsage
        1,											// BufferCount
        hWnd,										// OutputWindow
        TRUE,										// Windowed
        DXGI_SWAP_EFFECT_DISCARD,					// SwapEffect
        DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH		// Flags
    };

    // Direct3D11 デバイス・デバイスコンテキスト・スワップチェーンを生成
    ID3D11Device        * pDevice        = NULL;
    ID3D11DeviceContext * pDeviceContext = NULL;
    IDXGISwapChain      * pSwapChain     = NULL;
    D3D_FEATURE_LEVEL     feature;
    hr = D3D11CreateDeviceAndSwapChain( NULL,
                                        D3D_DRIVER_TYPE_HARDWARE,
                                        NULL,
                                        0,
                                        NULL,
                                        0,
                                        D3D11_SDK_VERSION,
                                        &scDesc,
                                        &pSwapChain,
                                        &pDevice,
                                        &feature,
                                        &pDeviceContext );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: D3D11CreateDeviceAndSwapChain()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "D3D11CreateDeviceAndSwapChain: ok (pDevice: 0x%p, pDeviceContext: 0x%p, pSwapChain: 0x%p, feature: 0x%4x)\n" ),
              pDevice,
              pDeviceContext,
              pSwapChain,
              ( int ) feature );


    // バックバッファテクスチャを取得
    ID3D11Texture2D * pBackBuffer = NULL;
    hr = pSwapChain->GetBuffer( 0, __uuidof( pBackBuffer ), reinterpret_cast< void ** >( &pBackBuffer ) );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: IDXGISwapChain::GetBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "IDXGISwapChain::GetBuffer: ok (pBackBuffer: 0x%p)\n" ), pBackBuffer );


    // レンダーターゲットビューを生成
    ID3D11RenderTargetView * pRenderTargetView = NULL;
    hr = pDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRenderTargetView );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateRenderTargetView()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateRenderTargetView: ok (pRenderTargetView: 0x%p)\n" ), pRenderTargetView );


    // デプス・ステンシルバッファとなるテクスチャを生成
    D3D11_TEXTURE2D_DESC depthStencilBufferDesc = {
        1280,						// Width
        720,						// Height
        1,							// MipLevels
        1,							// ArraySize
        DXGI_FORMAT_D32_FLOAT,		// Format
        {
            1,						// SampleDesc.Count
            0						// SampleDesc.Quality
        },
        D3D11_USAGE_DEFAULT,		// Usage
        D3D11_BIND_DEPTH_STENCIL,	// BindFlags
        0,							// CPUAccessFlags
        0							// MiscFlags
    };

    ID3D11Texture2D * pDepthStencilBuffer = NULL;
    hr = pDevice->CreateTexture2D( &depthStencilBufferDesc, NULL, &pDepthStencilBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateTexture2D()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateTexture2D: ok (pDepthStencilBuffer: 0x%p)\n" ), pDepthStencilBuffer );

    // デプス・ステンシルビューを生成
    ID3D11DepthStencilView * pDepthStencilView = NULL;
    hr = pDevice->CreateDepthStencilView( pDepthStencilBuffer, NULL, &pDepthStencilView );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateDepthStencilView()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateDepthStencilView: ok (pDepthStencilView: 0x%p)\n" ), pDepthStencilView );


    // レンダーターゲットビューとデプス・ステンシルビューをバインド
    ID3D11RenderTargetView * pRenderTargetViews[] = { pRenderTargetView };
    pDeviceContext->OMSetRenderTargets( 1, pRenderTargetViews, pDepthStencilView );
    dtprintf( _T( "ID3D11DeviceContext::OMSetRenderTargets: ok\n" ) );

    // バックバッファはもうここでは使わない
    COM_SAFE_RELEASE( pBackBuffer );


    // ビューポートをバインド
    D3D11_VIEWPORT viewport = {
        0.0f,		// TopLeftX
        0.0f,		// TopLeftY
        1280.0f,		// Width
        720.0f,		// Height
        0.0f,		// MinDepth
        1.0f			// MaxDepth
    };
    pDeviceContext->RSSetViewports( 1, &viewport );
    dtprintf( _T( "ID3D11DeviceContext::RSSetViewports: ok\n" ) );


    // 頂点データ
    float vertices[ 8 ][ 7 ] = {
        //    Xaxis  Yaxis  Zaxis  赤     緑     青     Alpha
        { -0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  0.0f,  1.0f },   // 手前左上
        {  0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f },   // 手前右上
        {  0.5f, -0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f },   // 手前右下
        { -0.5f, -0.5f,  0.5f,  0.0f,  1.0f,  1.0f,  1.0f },   // 手前左下
        { -0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  1.0f },   // 奥左上
        {  0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  1.0f,  1.0f },   // 奥右上
        {  0.5f, -0.5f, -0.5f,  1.0f,  1.0f,  0.0f,  1.0f },   // 奥右下
        { -0.5f, -0.5f, -0.5f,  1.0f,  1.0f,  1.0f,  1.0f }    // 奥左下
    };

    // 頂点バッファを生成
    D3D11_BUFFER_DESC vertexBufferDesc = {
        sizeof( vertices ),			// ByteWidth
        D3D11_USAGE_DEFAULT,		// Usage
        D3D11_BIND_VERTEX_BUFFER,	// BindFlags
        0,							// CPUAccessFlags
        0,							// MiscFlags
        0							// StructureByteStride
    };
    D3D11_SUBRESOURCE_DATA vertexResourceData = { vertices };

    ID3D11Buffer * pVertexBuffer = NULL;
    hr = pDevice->CreateBuffer( &vertexBufferDesc, &vertexResourceData, &pVertexBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pVertexBuffer: 0x%p)\n" ), pVertexBuffer );

    // 頂点バッファをバインド
    UINT strides[] = { sizeof( float ) * 7 };
    UINT offsets[] = { 0 };
    pDeviceContext->IASetVertexBuffers( 0, 1, &pVertexBuffer, strides, offsets );
    dtprintf( _T( "ID3D11DeviceContext::IASetVertexBuffers: ok\n" ) );


    // インデックスデータ
    unsigned int indices[] = { 0, 1, 2, 0, 2, 3,    // 手前
                               4, 0, 3, 4, 3, 7,    // 左
                               1, 5, 6, 1, 6, 2,    // 右
                               0, 4, 5, 0, 5, 1,    // 上
                               2, 6, 7, 2, 7, 3,    // 下
                               5, 4, 7, 5, 7, 6
                             };  // 裏

    // インデックスバッファを生成
    D3D11_BUFFER_DESC indexBufferDesc = {
        sizeof( indices ),				// ByteWidth
        D3D11_USAGE_DEFAULT,			// Usage
        D3D11_BIND_INDEX_BUFFER,		// BindFlags
        0,								// CPUAccessFlags
        0,								// MiscFlags
        0								// StructureByteStride
    };
    D3D11_SUBRESOURCE_DATA indexResourceData = { indices };

    ID3D11Buffer * pIndexBuffer = NULL;
    hr = pDevice->CreateBuffer( &indexBufferDesc, &indexResourceData, &pIndexBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pIndexBuffer: 0x%p)\n" ), pIndexBuffer );

    // インデックスバッファをバインド
    pDeviceContext->IASetIndexBuffer( pIndexBuffer, DXGI_FORMAT_R32_UINT, 0 );
    dtprintf( _T( "ID3D11DeviceContext::IASetIndexBuffer: ok\n" ) );


    // プリミティブタイプを設定
    pDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
    dtprintf( _T( "ID3D11DeviceContext::IASetPrimitiveTopology: ok\n" ) );


    // 頂点シェーダ用の定数バッファを作成
    D3D11_BUFFER_DESC VSConstantBufferDesc = {
        sizeof( D3DXMATRIX ) * 3,		// ByteWidth
        D3D11_USAGE_DYNAMIC,			// Usage
        D3D11_BIND_CONSTANT_BUFFER,		// BindFlags
        D3D11_CPU_ACCESS_WRITE,			// CPUAccessFlags
        0,								// MiscFlags
        0								// StructureByteStride
    };

    ID3D11Buffer * pVSConstantBuffer = NULL;
    hr = pDevice->CreateBuffer( &VSConstantBufferDesc, NULL, &pVSConstantBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pVSConstantBuffer: 0x%p)\n" ), pVSConstantBuffer );

    // 定数バッファをバインド
    pDeviceContext->VSSetConstantBuffers( 0, 1, &pVSConstantBuffer );
    dtprintf( _T( "ID3D11DeviceContext::VSSetConstantBuffers: ok\n" ) );


    // 頂点シェーダを作成
    ID3D11VertexShader * pVertexShader = NULL;
    hr = pDevice->CreateVertexShader( g_vs_perspective, sizeof( g_vs_perspective ), NULL, &pVertexShader );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateVertexShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateVertexShader: ok (pVertexShader: 0x%p)\n" ), pVertexShader );

    // ピクセルシェーダを作成
    ID3D11PixelShader * pPixelShader = NULL;
    hr = pDevice->CreatePixelShader( g_ps_constant, sizeof( g_ps_constant ), NULL, &pPixelShader );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreatePixelShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreatePixelShader: ok (pPixelShader: 0x%p)\n" ), pPixelShader );

    // シェーダをバインド
    pDeviceContext->VSSetShader( pVertexShader, NULL, 0 );
    dtprintf( _T( "ID3D11DeviceContext::VSSetShader: ok\n" ) );
    pDeviceContext->PSSetShader( pPixelShader, NULL, 0 );
    dtprintf( _T( "ID3D11DeviceContext::PSSetShader: ok\n" ) );
    pDeviceContext->GSSetShader( NULL, NULL, 0 );
    pDeviceContext->HSSetShader( NULL, NULL, 0 );
    pDeviceContext->DSSetShader( NULL, NULL, 0 );


    // 入力エレメント記述子
    D3D11_INPUT_ELEMENT_DESC verticesDesc[] = {
        { "IN_POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,    0, 0,               D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "IN_COLOR",    0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, sizeof(float)*3, D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };

    // 入力レイアウトを生成
    ID3D11InputLayout * pInputLayout = NULL;
    hr = pDevice->CreateInputLayout( verticesDesc, 2, g_vs_perspective, sizeof( g_vs_perspective ), &pInputLayout );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateInputLayout()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateInputLayout: ok (pInputLayout: 0x%p)\n" ), pInputLayout );

    // 入力レイアウトをバインド
    pDeviceContext->IASetInputLayout( pInputLayout );
    dtprintf( _T( "ID3D11DeviceContext::IASetInputLayout: ok\n" ) );


    // ラスタライザステートを生成
    D3D11_RASTERIZER_DESC rasterizerStateDesc = {
        D3D11_FILL_SOLID,		// FillMode
//		D3D11_FILL_WIREFRAME,	// FillMode (ワイヤーフレーム表示)
        D3D11_CULL_BACK,		// CullMode
//		D3D11_CULL_NONE,		// CullMode (カリングなし)
        FALSE,					// FrontCounterClockwise
        0,						// DepthBias
        0.0f,					// DepthBiasClamp
        0.0f,					// SlopeScaledDepthBias
        TRUE,					// DepthClipEnable
        FALSE,					// ScissorEnable
        FALSE,					// MultisampleEnable
        FALSE					// AntialiasedLineEnable
    };

    ID3D11RasterizerState * pRasterizerState = NULL;
    hr = pDevice->CreateRasterizerState( &rasterizerStateDesc, &pRasterizerState );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateRasterizerState()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateRasterizerState: ok (pRasterizerState: 0x%p)\n" ), pRasterizerState );

    // ラスタライザステートをバインド
    pDeviceContext->RSSetState( pRasterizerState );
    dtprintf( _T( "ID3D11DeviceContext::RSSetState: ok\n" ) );


    // デプス・ステンシルステートを生成
    D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc = {
        TRUE,								// DepthEnable
        D3D11_DEPTH_WRITE_MASK_ALL,			// DepthWriteMask
        D3D11_COMPARISON_LESS,				// DepthFunc
        FALSE,								// StencilEnable
        D3D11_DEFAULT_STENCIL_READ_MASK,	// StencilReadMask
        D3D11_DEFAULT_STENCIL_WRITE_MASK,	// StencilWriteMask
        {
            D3D11_STENCIL_OP_KEEP,			// FrontFace.StencilFailOp
            D3D11_STENCIL_OP_KEEP,			// FrontFace.StencilDepthFailOp
            D3D11_STENCIL_OP_KEEP,			// FrontFace.StencilPassOp
            D3D11_COMPARISON_ALWAYS			// FrontFace.StencilFunc
        },
        {
            D3D11_STENCIL_OP_KEEP,			// BackFace.StencilFailOp
            D3D11_STENCIL_OP_KEEP,			// BackFace.StencilDepthFailOp
            D3D11_STENCIL_OP_KEEP,			// BackFace.StencilPassOp
            D3D11_COMPARISON_ALWAYS			// BackFace.StencilFunc
        }
    };

    ID3D11DepthStencilState * pDepthStencilState = NULL;
    hr = pDevice->CreateDepthStencilState( &depthStencilStateDesc, &pDepthStencilState );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateDepthStencilState()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateDepthStencilState: ok (pDepthStencilState: 0x%p)\n" ), pDepthStencilState );

    // デプス・ステンシルステートをバインド
    pDeviceContext->OMSetDepthStencilState( pDepthStencilState, 0 );
    dtprintf( _T( "ID3D11DeviceContext::OMSetDepthStencilState: ok\n" ) );



    MSG msg;

    while ( 1 )
    {
        // メッセージを取得
        if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        {
            if ( msg.message == WM_QUIT )
            {
                dtprintf( _T( "PeekMessage: WM_QUIT\n" ) );
                break;
            }
            // メッセージ処理
            DispatchMessage( &msg );
        }
        else
        {
            HRESULT hr;

            static unsigned int count = 0;

            float theta = ( count++ / 200.0f ) * ( 3.141593f / 2.0f );


            // World-View-Projection 行列をそれぞれ生成
            D3DXMATRIX world, view, projection;

            D3DXMatrixIdentity( &world );

            const D3DXVECTOR3 eye( 1.8f * 1.414214f * -cosf( theta ), 1.8f, 1.8f * 1.414214f * sinf( theta ) );
            const D3DXVECTOR3 at( 0.0f, 0.0f, 0.0f );
            const D3DXVECTOR3 up( 0.0f, 1.0f, 0.0f );
            D3DXMatrixLookAtRH( &view, &eye, &at, &up );

            D3DXMatrixPerspectiveFovRH( &projection, 3.141593f / 4.0f, 1280.0f / 720.0f, 1.0f, 10000.0f );


            // 頂点シェーダ用定数バッファへアクセス
            D3D11_MAPPED_SUBRESOURCE mapped;
            hr = pDeviceContext->Map( pVSConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped );
            if ( SUCCEEDED( hr ) )
            {
                D3DXMATRIX * mapped_m = static_cast< D3DXMATRIX * >( mapped.pData );

                mapped_m[0] = world;
                mapped_m[1] = view;
                mapped_m[2] = projection;

                // 後始末
                pDeviceContext->Unmap( pVSConstantBuffer, 0 );
            }


            // レンダーターゲットビューをクリア
            const float clear[ 4 ] = { 0.0f, 0.0f, 0.3f, 1.0f };	// RGBA
            pDeviceContext->ClearRenderTargetView( pRenderTargetView, clear );

            // デプス・ステンシルビューをクリア
            pDeviceContext->ClearDepthStencilView( pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0 );


            // 描画
            pDeviceContext->DrawIndexed( 36, 0, 0 );

            pSwapChain->Present( 1, 0 );

            // ちょっとだけ待つ
            Sleep( 5 );
        }
    }



    // シェーダをアンバインド
    pDeviceContext->VSSetShader( NULL, NULL, 0 );
    pDeviceContext->PSSetShader( NULL, NULL, 0 );

    // デバイス・リソース解放
    COM_SAFE_RELEASE( pDepthStencilState );
    COM_SAFE_RELEASE( pRasterizerState );
    COM_SAFE_RELEASE( pInputLayout );
    COM_SAFE_RELEASE( pPixelShader );
    COM_SAFE_RELEASE( pVertexShader );
    COM_SAFE_RELEASE( pVSConstantBuffer );
    COM_SAFE_RELEASE( pIndexBuffer );
    COM_SAFE_RELEASE( pVertexBuffer );
    COM_SAFE_RELEASE( pDepthStencilView );
    COM_SAFE_RELEASE( pDepthStencilBuffer );
    COM_SAFE_RELEASE( pRenderTargetView );
    COM_SAFE_RELEASE( pSwapChain );
    COM_SAFE_RELEASE( pDeviceContext );
    COM_SAFE_RELEASE( pDevice );


    return msg.wParam;
}
Пример #29
0
void CRenderCaptureDX::BeginRender()
{
  ID3D11DeviceContext* pContext = g_Windowing.Get3D11Context();
  ID3D11Device* pDevice = g_Windowing.Get3D11Device();
  CD3D11_QUERY_DESC queryDesc(D3D11_QUERY_EVENT);

  if (!m_asyncChecked)
  {
    m_asyncSupported = SUCCEEDED(pDevice->CreateQuery(&queryDesc, nullptr));
    if (m_flags & CAPTUREFLAG_CONTINUOUS)
    {
      if (!m_asyncSupported)
        CLog::Log(LOGWARNING, "CRenderCaptureDX: D3D11_QUERY_OCCLUSION not supported, performance might suffer");
      if (!UseOcclusionQuery())
        CLog::Log(LOGWARNING, "CRenderCaptureDX: D3D11_QUERY_OCCLUSION disabled, performance might suffer");
    }
    m_asyncChecked = true;
  }

  HRESULT result;

  if (m_surfaceWidth != m_width || m_surfaceHeight != m_height)
  {
    SAFE_RELEASE(m_renderSurface);
    SAFE_RELEASE(m_copySurface);

    CD3D11_TEXTURE2D_DESC texDesc(DXGI_FORMAT_B8G8R8A8_UNORM, m_width, m_height, 1, 1, D3D11_BIND_RENDER_TARGET);
    result = pDevice->CreateTexture2D(&texDesc, nullptr, &m_renderTexture);
    if (FAILED(result))
    {
      CLog::Log(LOGERROR, "CRenderCaptureDX::BeginRender: CreateTexture2D (RENDER_TARGET) failed %s",
                g_Windowing.GetErrorDescription(result).c_str());
      SetState(CAPTURESTATE_FAILED);
      return;
    }

    CD3D11_RENDER_TARGET_VIEW_DESC rtDesc(D3D11_RTV_DIMENSION_TEXTURE2D);
    result = pDevice->CreateRenderTargetView(m_renderTexture, &rtDesc, &m_renderSurface);
    if (FAILED(result))
    {
      CLog::Log(LOGERROR, "CRenderCaptureDX::BeginRender: CreateRenderTargetView failed %s",
        g_Windowing.GetErrorDescription(result).c_str());
      SetState(CAPTURESTATE_FAILED);
      return;
    }

    texDesc.BindFlags = 0;
    texDesc.Usage = D3D11_USAGE_STAGING;
    texDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;

    result = pDevice->CreateTexture2D(&texDesc, nullptr, &m_copySurface);
    if (FAILED(result))
    {
      CLog::Log(LOGERROR, "CRenderCaptureDX::BeginRender: CreateTexture2D (USAGE_STAGING) failed %s",
                g_Windowing.GetErrorDescription(result).c_str());
      SetState(CAPTURESTATE_FAILED);
      return;
    }

    m_surfaceWidth = m_width;
    m_surfaceHeight = m_height;
  }

  if (m_bufferSize != m_width * m_height * 4)
  {
    m_bufferSize = m_width * m_height * 4;
    av_freep(&m_pixels);
    m_pixels = (uint8_t*)av_malloc(m_bufferSize);
  }

  pContext->OMSetRenderTargets(1, &m_renderSurface, nullptr);

  if (m_asyncSupported && UseOcclusionQuery())
  {
    //generate an occlusion query if we don't have one
    if (!m_query)
    {
      result = pDevice->CreateQuery(&queryDesc, &m_query);
      if (FAILED(result))
      {
        CLog::Log(LOGERROR, "CRenderCaptureDX::BeginRender: CreateQuery failed %s",
                  g_Windowing.GetErrorDescription(result).c_str());
        m_asyncSupported = false;
        SAFE_RELEASE(m_query);
      }
    }
  }
  else
  {
    //don't use an occlusion query, clean up any old one
    SAFE_RELEASE(m_query);
  }
}
Пример #30
0
	void VRender() override
	{
		float color[4] = { 0.2f, 0.2f, 0.2f, 1.0f };

		// Set up the input assembler
		mDeviceContext->IASetInputLayout(mInputLayout);
		mRenderer->VSetPrimitiveType(GPU_PRIMITIVE_TYPE_TRIANGLE);

		mDeviceContext->RSSetViewports(1, &mRenderer->GetViewport());
		mDeviceContext->OMSetRenderTargets(1, mRenderer->GetRenderTargetView(), mRenderer->GetDepthStencilView());
		mDeviceContext->ClearRenderTargetView(*mRenderer->GetRenderTargetView(), color);
		mDeviceContext->ClearDepthStencilView(
		mRenderer->GetDepthStencilView(),
			D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL,
			1.0f,
			0);

		mDeviceContext->VSSetShader(mVertexShader, NULL, 0);
		mDeviceContext->PSSetShader(mPixelShader, NULL, 0);

		mDeviceContext->UpdateSubresource(
			mConstantBuffer,
			0,
			NULL,
			&mMatrixBuffer,
			0,
			0); 

		mDeviceContext->VSSetConstantBuffers(
			0,
			1,
			&mConstantBuffer);

		// Bezier
		mDeviceContext->UpdateSubresource(static_cast<DX11Mesh*>(mBezierMesh)->mVertexBuffer, 0, NULL, &mBezierVertices, 0, 0);

		mRenderer->VSetPrimitiveType(GPU_PRIMITIVE_TYPE_LINE);
		mRenderer->VBindMesh(mBezierMesh);
		mRenderer->VDrawIndexed(0, mBezierMesh->GetIndexCount());

		// Handles
		mDeviceContext->UpdateSubresource(static_cast<DX11Mesh*>(mHandlesMesh)->mVertexBuffer, 0, NULL, &mHandlesVertices, 0, 0);

		mRenderer->VSetPrimitiveType(GPU_PRIMITIVE_TYPE_LINE);
		mRenderer->VBindMesh(mHandlesMesh);
		mRenderer->VDrawIndexed(0, mHandlesMesh->GetIndexCount());

		// Circles
		mRenderer->VSetPrimitiveType(GPU_PRIMITIVE_TYPE_TRIANGLE);
		for (size_t i = 0; i < 4; i++)
		{
			mMatrixBuffer.mWorld = (mat4f::scale(mCircleScale) * mat4f::translate(mBezier.p[i])).transpose();
			mDeviceContext->UpdateSubresource(mConstantBuffer, 0, NULL, &mMatrixBuffer, 0, 0);

			mRenderer->VBindMesh(mCircleMesh);
			mRenderer->VDrawIndexed(0, mCircleMesh->GetIndexCount());
		}


		mRenderer->VSwapBuffers();
	}