void SkeletonModelFragmentShader::setParameters( ID3D11DeviceContext& deviceContext,
                                                 const Texture2DSpecBind< TexBind::ShaderResource, unsigned char >& alphaTexture,
                                                 const Texture2DSpecBind< TexBind::ShaderResource, uchar4 >& emissiveTexture,
                                                 const Texture2DSpecBind< TexBind::ShaderResource, uchar4 >& albedoTexture,
                                                 const Texture2DSpecBind< TexBind::ShaderResource, uchar4 >& normalTexture,
                                                 const Texture2DSpecBind< TexBind::ShaderResource, unsigned char >& metalnessTexture,
                                                 const Texture2DSpecBind< TexBind::ShaderResource, unsigned char >& roughnessTexture,
                                                 const Texture2DSpecBind< TexBind::ShaderResource, unsigned char >& indexOfRefractionTexture,
                                                 const float4& extraEmissive )
{
	const int resourceCount = 7;
	ID3D11ShaderResourceView* textureResource[ resourceCount ] = 
    {
        alphaTexture.getShaderResourceView(),
        emissiveTexture.getShaderResourceView(),
        albedoTexture.getShaderResourceView(),
        normalTexture.getShaderResourceView(),
        metalnessTexture.getShaderResourceView(),
        roughnessTexture.getShaderResourceView(),
        indexOfRefractionTexture.getShaderResourceView()
    };

	deviceContext.PSSetShaderResources( 0, resourceCount, textureResource );
	deviceContext.PSSetSamplers( 0, 1, m_samplerState.GetAddressOf() );

    D3D11_MAPPED_SUBRESOURCE mappedResource;
    ConstantBuffer* dataPtr;

    HRESULT result = deviceContext.Map( m_constantInputBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource );
    if ( result < 0 ) throw std::exception( "BlockModelVertexShader::setParameters - mapping constant buffer to CPU memory failed" );

    dataPtr = (ConstantBuffer*)mappedResource.pData;

    dataPtr->extraEmissive = extraEmissive;

    deviceContext.Unmap( m_constantInputBuffer.Get(), 0 );

    deviceContext.PSSetConstantBuffers( 0, 1, m_constantInputBuffer.GetAddressOf() );
}
Exemple #2
0
bool CGUIFontTTFDX::UpdateDynamicVertexBuffer(const SVertex* pSysMem, unsigned int vertex_count)
{
  ID3D11Device* pDevice = g_Windowing.Get3D11Device();
  ID3D11DeviceContext* pContext = g_Windowing.Get3D11Context();

  if (!pDevice || !pContext)
    return false;

  unsigned width = sizeof(SVertex) * vertex_count;
  if (width > m_vertexWidth) // create or re-create
  {
    SAFE_RELEASE(m_vertexBuffer);

    CD3D11_BUFFER_DESC bufferDesc(width, D3D11_BIND_VERTEX_BUFFER, D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE);
    D3D11_SUBRESOURCE_DATA initData;
    ZeroMemory(&initData, sizeof(D3D11_SUBRESOURCE_DATA));
    initData.pSysMem = pSysMem;

    if (FAILED(pDevice->CreateBuffer(&bufferDesc, &initData, &m_vertexBuffer)))
    {
      CLog::Log(LOGERROR, __FUNCTION__ " - Failed to create the vertex buffer.");
      return false;
    }

    m_vertexWidth = width;
  }
  else
  {
    D3D11_MAPPED_SUBRESOURCE resource;
    if (FAILED(pContext->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource)))
    {
      CLog::Log(LOGERROR, __FUNCTION__ " - Failed to update the vertex buffer.");
      return false;
    }
    memcpy(resource.pData, pSysMem, width);
    pContext->Unmap(m_vertexBuffer, 0);
  }
  return true;
}
Void * D3D11Texture2D::Lock( const D3D11SubResourceIndex * pIndex, D3D11ResourceLock iLockType, UInt iResourceLockFlags, UInt * outPitch, D3D11DeferredContext * pContext )
{
    DebugAssert( IsCreated() );
    DebugAssert( CanLock() );
    DebugAssert( !m_bLocked );

    if ( iLockType == D3D11RESOURCE_LOCK_WRITE_DISCARD ) {
        DebugAssert( m_iUsage == D3D11RESOURCE_USAGE_DYNAMIC );
    } else if ( iLockType == D3D11RESOURCE_LOCK_WRITE_NO_OVERWRITE ) {
        DebugAssert( m_iUsage == D3D11RESOURCE_USAGE_DYNAMIC );
        DebugAssert( (m_iBinds & D3D11RESOURCE_BIND_SHADER_INPUT) == 0 );
    } else {
        if ( iLockType & D3D11RESOURCE_LOCK_READ ) {
            DebugAssert( CanCPURead() );
        } else if ( iLockType & D3D11RESOURCE_LOCK_WRITE ) {
            DebugAssert( CanCPUWrite() );
        }
    }

    UInt iSubResource = _GetSubResourceIndex( pIndex, m_hTextureDesc.MipLevels, m_hTextureDesc.ArraySize );

    D3D11_MAPPED_SUBRESOURCE hMappedSubResource;
    hMappedSubResource.pData = NULL;
    hMappedSubResource.RowPitch = 0;
    hMappedSubResource.DepthPitch = 0;

    ID3D11DeviceContext * pDeviceContext = m_pRenderer->m_pImmediateContext;
    if ( pContext != NULL && pContext->IsCreated() )
        pDeviceContext = pContext->m_pDeferredContext;

    HRESULT hRes = pDeviceContext->Map( m_pTexture, iSubResource, D3D11ResourceLockToD3D11[iLockType], _D3D11ConvertFlags32(D3D11ResourceLockFlagsToD3D11, iResourceLockFlags), &hMappedSubResource );
    DebugAssert( hRes == S_OK && hMappedSubResource.pData != NULL );
    
    *outPitch = hMappedSubResource.RowPitch;

    m_bLocked = true;

    return hMappedSubResource.pData;
}
//-----------------------------------------------------------------------------
void CPUTTextureDX11::UnmapTexture( CPUTRenderParameters &params )
{
    ASSERT( mMappedType != CPUT_MAP_UNDEFINED, _L("Can't unmap a render target that isn't mapped.") );

    CPUTRenderParametersDX *pParamsDX11 = (CPUTRenderParametersDX*)&params;
    ID3D11DeviceContext *pContext = pParamsDX11->mpContext;

    pContext->Unmap( mpTextureStaging, 0 );

    // If we were mapped for write, then copy staging buffer to GPU
    switch( mMappedType )
    {
    case CPUT_MAP_READ:
        break;
    case CPUT_MAP_READ_WRITE:
    case CPUT_MAP_WRITE:
    case CPUT_MAP_WRITE_DISCARD:
    case CPUT_MAP_NO_OVERWRITE:
        pContext->CopyResource( mpTexture, mpTextureStaging );
        break;
    };
} // CPUTTextureDX11::Unmap()
//-----------------------------------------------------------------------------
void CPUTRenderStateBlockDX11::SetRenderStates( CPUTRenderParameters &renderParams )
{
    ID3D11DeviceContext *pContext = ((CPUTRenderParametersDX*)&renderParams)->mpContext;

    pContext->OMSetBlendState( mpBlendState, mStateDesc.BlendFactor, mStateDesc.SampleMask );
    pContext->OMSetDepthStencilState( mpDepthStencilState, 0 ); // TODO: read stecil ref from config file
    pContext->RSSetState( mpRasterizerState );
    pContext->PSSetSamplers( 0, mNumSamplers, mpSamplerState );
    pContext->VSSetSamplers( 0, mNumSamplers, mpSamplerState );
    pContext->GSSetSamplers( 0, mNumSamplers, mpSamplerState );
} // CPUTRenderStateBlockDX11::SetRenderState()
Exemple #6
0
void CD3DBuffer::OnDestroyDevice()
{
  ID3D11Device* pDevice = g_Windowing.Get3D11Device();
  ID3D11DeviceContext* pContext = g_Windowing.GetImmediateContext();

  if (!pDevice || !pContext || !m_buffer)
    return;

  D3D11_BUFFER_DESC srcDesc;
  m_buffer->GetDesc(&srcDesc);

  ID3D11Buffer *buffer = nullptr;
  if (srcDesc.Usage != D3D11_USAGE_STAGING || 0 == (srcDesc.CPUAccessFlags & D3D11_CPU_ACCESS_READ))
  {
    CD3D11_BUFFER_DESC trgDesc(srcDesc);
    trgDesc.Usage = D3D11_USAGE_STAGING;
    trgDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
    trgDesc.BindFlags = 0;

    if (FAILED(pDevice->CreateBuffer(&trgDesc, NULL, &buffer)))
      return;

    pContext->CopyResource(buffer, m_buffer);
  }
  else
    buffer = m_buffer;

  D3D11_MAPPED_SUBRESOURCE res;
  if (SUCCEEDED(pContext->Map(buffer, 0, D3D11_MAP_READ, 0, &res)))
  {
    m_data = new unsigned char[srcDesc.ByteWidth];
    memcpy(m_data, res.pData, srcDesc.ByteWidth);
    pContext->Unmap(buffer, 0);
  }

  if (buffer != m_buffer)
    SAFE_RELEASE(buffer);
  SAFE_RELEASE(m_buffer);
}
 bool  xD11UnkwonTexture::_update(ID3D11Resource* pLockTexture , void* data  , int dateLen , int rowPitch , int depthPicth , int mipmapLevel , int arraySlice)
 {
     if(pLockTexture == NULL)
         return false;

     ID3D11DeviceContext* pDeviceContext = m_pD11RenderApi->d11DeviceContext();
     UINT lockResource = D3D10CalcSubresource((UINT)mipmapLevel , (UINT)arraySlice, (UINT)m_TexInfo.m_MipmapLevel);

     if(m_TexInfo.m_Usage == D3D11_USAGE_DEFAULT)
     {
         if(rowPitch == 0 ) rowPitch = dateLen;
         if(depthPicth == 0) depthPicth = dateLen;
         pDeviceContext->UpdateSubresource(pLockTexture ,lockResource , NULL , data ,rowPitch , depthPicth);         
     }
     else //只有非DEFAULT的纹理才是可以Map的。
     {
         char* pMapedData = NULL;
         int   Pitch = 0;
         int   SlicePith = 0;
         UINT  mapFlag = 0;


         if(pMapedData == NULL)
             return false;

         D3D11_MAPPED_SUBRESOURCE mappedTex;
         mappedTex.pData = NULL;
         mappedTex.RowPitch = 0;
         mappedTex.DepthPitch = 0;
         pDeviceContext->Map(pLockTexture , lockResource , D3D11_MAP_WRITE_DISCARD , mapFlag , &mappedTex );
         pMapedData = (char*)mappedTex.pData;
         Pitch     = mappedTex.RowPitch;
         SlicePith = mappedTex.DepthPitch;
         memcpy(pMapedData , data , dateLen);
         pDeviceContext->Unmap(pLockTexture , lockResource);
     }
     return true;
 }
Exemple #8
0
std::vector<DXGI_SAMPLE_DESC> EnumAAModes(IDXGIAdapter* adapter)
{
	std::vector<DXGI_SAMPLE_DESC> aa_modes;

	// NOTE: D3D 10.0 doesn't support multisampled resources which are bound as depth buffers AND shader resources.
	// Thus, we can't have MSAA with 10.0 level hardware.
	ID3D11Device* device;
	ID3D11DeviceContext* context;
	D3D_FEATURE_LEVEL feat_level;
	HRESULT hr = PD3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, D3D11_CREATE_DEVICE_SINGLETHREADED, supported_feature_levels, NUM_SUPPORTED_FEATURE_LEVELS, D3D11_SDK_VERSION, &device, &feat_level, &context);
	if (FAILED(hr) || feat_level == D3D_FEATURE_LEVEL_10_0)
	{
		DXGI_SAMPLE_DESC desc;
		desc.Count = 1;
		desc.Quality = 0;
		aa_modes.push_back(desc);
		SAFE_RELEASE(context);
		SAFE_RELEASE(device);
	}
	else
	{
		for (int samples = 0; samples < D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; ++samples)
		{
			UINT quality_levels = 0;
			device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, samples, &quality_levels);
			if (quality_levels > 0)
			{
				DXGI_SAMPLE_DESC desc;
				desc.Count = samples;
				for (desc.Quality = 0; desc.Quality < quality_levels; ++desc.Quality)
					aa_modes.push_back(desc);
			}
		}
		context->Release();
		device->Release();
	}
	return aa_modes;
}
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);

}
HRESULT DeferredPipeline::Lighting::set_ps_constant_buffer(ID3D11DeviceContext & device_context, Lighting_PS_Constant_Buffer & ps_constant_buffer)
{
    HRESULT hr;
    D3D11_MAPPED_SUBRESOURCE resource;
    Lighting_PS_Constant_Buffer* mappedBuffer;

    hr = device_context.Map(_ps_constant_buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource);
    if (FAILED(hr)) {
        return hr;
    }

    mappedBuffer = (Lighting_PS_Constant_Buffer*)resource.pData;

    mappedBuffer->view = ps_constant_buffer.view;
    mappedBuffer->inverse_projection = ps_constant_buffer.inverse_projection;
    mappedBuffer->camera_position = ps_constant_buffer.camera_position;

    device_context.Unmap(_ps_constant_buffer, 0);

    device_context.PSSetConstantBuffers(0, 1, &_ps_constant_buffer);

    return S_OK;
}
    void CCoherentViewListener::DrawFrameDX11SharedTexture( Coherent::UI::CoherentHandle handle, int width, int height )
    {
        if ( gCoherentUISystem == NULL )
        {
            return;
        }

        void* pNativeTexture = gCoherentUISystem->GetNativeTextureFromSharedHandle( handle );

        if ( pNativeTexture == NULL )
        {
            return;
        }

        ID3D11Texture2D* pSourceResource = static_cast<ID3D11Texture2D*>( pNativeTexture );
        ID3D11Texture2D* pDestResource = static_cast<ID3D11Texture2D*>( m_pTexture );

        ID3D11DeviceContext* pContext = NULL;
        ID3D11Device* pDevice = static_cast<ID3D11Device*>( gD3DDevice );
        pDevice->GetImmediateContext( &pContext );

        pContext->CopySubresourceRegion( pDestResource, 0, 0, 0, 0, pSourceResource, 0, NULL );
    }
Exemple #12
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;
}
//--------------------------------------------------------------------------------------
// Name: CTiledResourceDevice::UpdateVSConstants
// Desc: Copies the vertex shader shadow constants into the constant buffers and sets them
//       into the D3D device context.
//--------------------------------------------------------------------------------------
VOID CTiledResourceDevice::UpdateVSConstants()
{
    // Update the tiled resource constants:
    HRESULT hr = UpdateDynamicConstantBuffer( m_pd3dDeviceContext, m_pVSTiledResourceCB, m_VSTiledResourceConstants, sizeof(m_VSTiledResourceConstants) );
    ASSERT( SUCCEEDED(hr) );

    // Update the page pool constants:
    hr = UpdateDynamicConstantBuffer( m_pd3dDeviceContext, m_pVSPagePoolCB, m_VSPagePoolConstants, sizeof(m_VSPagePoolConstants) );
    ASSERT( SUCCEEDED(hr) );

    // Set the constant buffers to slots 12 and 13 on the D3D device context:
    ID3D11Buffer* pBuffers[] = { m_pVSTiledResourceCB, m_pVSPagePoolCB };
    m_pd3dDeviceContext->VSSetConstantBuffers( 12, 2, pBuffers );
}
//-----------------------------------------------------------------------------
void CPUTRenderTargetDepth::UnmapRenderTarget( CPUTRenderParameters &params )
{
    ASSERT( mMappedType != CPUT_MAP_UNDEFINED, "Can't unmap a render target that isn't mapped." );

    ID3D11DeviceContext *pContext = CPUT_DX11::GetContext();

    pContext->Unmap( mpDepthTextureDXStaging, 0 );

    // If we were mapped for write, then copy staging buffer to GPU
    switch( mMappedType )
    {
    case CPUT_MAP_READ:
        break;
    case CPUT_MAP_READ_WRITE:
    case CPUT_MAP_WRITE:
    case CPUT_MAP_WRITE_DISCARD:
    case CPUT_MAP_NO_OVERWRITE:
        pContext->CopyResource( mpDepthTextureDX, mpDepthTextureDXStaging );
        break;
    };

    // mMappedType = CPUT_MAP_UNDEFINED;
} // CPUTRenderTargetDepth::Unmap()
bool BufferStorage11::NativeBuffer11::resize(size_t size, bool preserveData)
{
    ID3D11Device *device = mRenderer->getDevice();
    ID3D11DeviceContext *context = mRenderer->getDeviceContext();

    D3D11_BUFFER_DESC bufferDesc;
    fillBufferDesc(&bufferDesc, mRenderer, mUsage, size);

    ID3D11Buffer *newBuffer;
    HRESULT result = device->CreateBuffer(&bufferDesc, NULL, &newBuffer);

    if (FAILED(result))
    {
        return gl::error(GL_OUT_OF_MEMORY, false);
    }

    if (mNativeBuffer && preserveData)
    {
        D3D11_BOX srcBox;
        srcBox.left = 0;
        srcBox.right = size;
        srcBox.top = 0;
        srcBox.bottom = 1;
        srcBox.front = 0;
        srcBox.back = 1;

        context->CopySubresourceRegion(newBuffer, 0, 0, 0, 0, mNativeBuffer, 0, &srcBox);
    }

    // No longer need the old buffer
    SafeRelease(mNativeBuffer);
    mNativeBuffer = newBuffer;

    mBufferSize = bufferDesc.ByteWidth;

    return true;
}
void *BufferStorage11::getData()
{
    NativeBuffer11 *stagingBuffer = getStagingBuffer();

    if (!stagingBuffer)
    {
        // Out-of-memory
        return NULL;
    }

    if (stagingBuffer->getDataRevision() > mResolvedDataRevision)
    {
        if (stagingBuffer->getSize() > mResolvedData.size())
        {
            mResolvedData.resize(stagingBuffer->getSize());
        }

        ID3D11DeviceContext *context = mRenderer->getDeviceContext();

        D3D11_MAPPED_SUBRESOURCE mappedResource;
        HRESULT result = context->Map(stagingBuffer->getNativeBuffer(), 0, D3D11_MAP_READ, 0, &mappedResource);
        if (FAILED(result))
        {
            return gl::error(GL_OUT_OF_MEMORY, (void*)NULL);
        }

        memcpy(mResolvedData.data(), mappedResource.pData, stagingBuffer->getSize());

        context->Unmap(stagingBuffer->getNativeBuffer(), 0);

        mResolvedDataRevision = stagingBuffer->getDataRevision();
    }

    mReadUsageCount = 0;

    return mResolvedData.data();
}
void D3D11App::DebugViewTexture2D(ID3D11ShaderResourceView *srv, const float x, const float y, const float width, const float height, const int slice)
{
	// Make sure we have enough space in the vertex buffer
	SetToolsVBSize(4 * sizeof(Pos2Tex3));

	// Fill vertex buffer
	Pos2Tex3 *dest;
	ID3D11DeviceContext* context = m_context->GetDeviceContext();
	D3D11_MAPPED_SUBRESOURCE resource;
	context->Map(m_toolsVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource);
	dest = reinterpret_cast<Pos2Tex3*> ( resource.pData );
		dest[0].pos = float2(x, y + height);
		dest[0].tex = float3(0, 0, (float) slice);
		dest[1].pos = float2(x + width, y + height);
		dest[1].tex = float3(1, 0, (float) slice);
		dest[2].pos = float2(x, y);
		dest[2].tex = float3(0, 1, (float) slice);
		dest[3].pos = float2(x + width, y);
		dest[3].tex = float3(1, 1, (float) slice);
	context->Unmap(m_toolsVB, 0);


	ID3D11DeviceContext *dev = m_context->GetDeviceContext();

	// Setup the effect
	m_context->SetEffect(m_toolsEffect);
	if (slice < 0)
	{
		m_context->SetTexture("tex2d", srv);
		m_context->Apply(2, 0);
	}
	else
	{
		m_context->SetTexture("texArray", srv);
		m_context->Apply(2, 1);
	}

	dev->IASetInputLayout(m_pos2Tex3Layout);

	UINT stride = sizeof(Pos2Tex3);
	UINT offset = 0;
	dev->IASetVertexBuffers(0, 1, &m_toolsVB, &stride, &offset);

	// Render a textured quad
	dev->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
	dev->Draw(4, 0);
}
Exemple #18
0
		void FontShader::renderShader(int i_indexCount)
		{
			ID3D11DeviceContext* deviceContext = GraphicsDX::GetDeviceContext();

			// Set the vertex input layout.
			deviceContext->IASetInputLayout(_layout);

			// Set the vertex and pixel shaders that will be used to render the triangles.
			deviceContext->VSSetShader(_vertexShader, NULL, 0);
			deviceContext->HSSetShader(nullptr, NULL, 0);
			deviceContext->DSSetShader(nullptr, NULL, 0);
			deviceContext->GSSetShader(nullptr, NULL, 0);
			deviceContext->PSSetShader(_pixelShader, NULL, 0);

			// Set the sampler state in the pixel shader.
			deviceContext->PSSetSamplers(0, 1, &_sampleState);

			// Render the triangles.
			deviceContext->DrawIndexed(i_indexCount, 0, 0);
		}
Exemple #19
0
gl::Error Image11::map(D3D11_MAP mapType, D3D11_MAPPED_SUBRESOURCE *map)
{
    // We must recover from the TextureStorage if necessary, even for D3D11_MAP_WRITE.
    gl::Error error = recoverFromAssociatedStorage();
    if (error.isError())
    {
        return error;
    }

    ID3D11Resource *stagingTexture = NULL;
    unsigned int subresourceIndex = 0;
    error = getStagingTexture(&stagingTexture, &subresourceIndex);
    if (error.isError())
    {
        return error;
    }

    ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();

    ASSERT(mStagingTexture);
    HRESULT result = deviceContext->Map(stagingTexture, subresourceIndex, mapType, 0, map);

    // this can fail if the device is removed (from TDR)
    if (d3d11::isDeviceLostError(result))
    {
        mRenderer->notifyDeviceLost();
    }
    else if (FAILED(result))
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Failed to map staging texture, result: 0x%X.", result);
    }

    mDirty = true;

    return gl::Error(GL_NO_ERROR);
}
//-----------------------------------------
void CPUTRenderTargetColor::RestoreRenderTarget( CPUTRenderParameters &renderParams )
{
    ASSERT( mRenderTargetSet, "Render target restored without calling SetRenderTarget()");

    if( mMultiSampleCount>1 )
    {
        Resolve( renderParams );
    }

    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 };
    CPUT_DX11::GetContext()->RSSetViewports(1, &viewport);

    mRenderTargetSet = false;
} // CPUTRenderTarget::RestoreRenderTarget()
Exemple #21
0
const void ShaderClass::RenderShader(UINT indexCount, UINT indexStart)const
{
	ID3D11DeviceContext* c = SystemClass::GetInstance()->mGrapInst->GetContext();

	// Set the vertex input layout.
	c->IASetInputLayout(mLayout);

	// Set the vertex and pixel shaders that will be used to render this triangle.
	c->VSSetShader(mVertexShader, nullptr, 0);
	c->HSSetShader(mHullShader, nullptr, 0);
	c->DSSetShader(mDomainShader, nullptr, 0);
	c->GSSetShader(mGeometryShader, nullptr, 0);
	c->PSSetShader(mPixelShader, nullptr, 0);

	// Render mesh stored in active buffers
	c->DrawIndexed(indexCount, indexStart, 0);
}
Exemple #22
0
void Edo::GetD3D11DeviceAndSwapchainVTable(HWND window, uintptr_t** ppDeviceVTable, uintptr_t** ppContextVTable, uintptr_t** ppSwapchainVTable)
{
	ID3D11Device* pDevice;
	ID3D11DeviceContext* pContext;
	IDXGISwapChain* pSwapchain;

	//Create dummy devices.
	CreateD3D11DummyDeviceAndSwapchain(window, &pDevice, &pContext, &pSwapchain);

	//Set the vtable pointers
	if(ppDeviceVTable)
		*ppDeviceVTable = (uintptr_t*)*(uintptr_t*)pDevice;

	if(ppContextVTable)
		*ppContextVTable = (uintptr_t*)*(uintptr_t*)pContext;

	if(ppSwapchainVTable)
		*ppSwapchainVTable = (uintptr_t*)*(uintptr_t*)pSwapchain;

	//Cleanup.
	pDevice->Release();
	pContext->Release();
	pSwapchain->Release();
}
Exemple #23
0
    void GuiRenderer::RenderPanels() {
        Effect* effect = effectResource->GetEffect();

        ID3D11DeviceContext* context = GraphicsManager::Get()->GetImmidiateContext();

        quadVertexData->Bind(VertexChannelType::Geometry | VertexChannelType::Texture);

        vector<Panel> panels = GuiManager::Get()->GetPanels();
        sort(begin(panels), end(panels), [](const Panel& a, const Panel& b) -> bool {
            return a.layer < b.layer;
        });

        for(auto it = begin(panels); it != end(panels); ++it) {
            const Panel& panel = *it;
            Vector2f scale = (panel.rectangle.topRight - panel.rectangle.bottomLeft) / 2.0f;
            Vector2f center = (panel.rectangle.topRight + panel.rectangle.bottomLeft) / 2.0f;
            Matrix transform = Matrix::CreateScale(scale.x, scale.y, 1.0f) * Matrix::CreateTranslation(center.x, center.y, 0.0f);
            effect->SetParam("World", transform);
            effect->SetParam("Texture", panel.textureResource->GetTexture());
            effect->Bind("Gui", "Textured", "Pass0");

            context->DrawIndexed(quadVertexData->GetIndexCount(), 0, 0);
        }
    }
Exemple #24
0
//---------------------------------------------------------------------------
void ShadowMapGen::DrawRenderable(const RenderableNode& r)
{
    if (!r.GetFlag( RenderableNode::kShadowCaster ) )
        return;

    ID3D11DeviceContext* dc = m_rc->Context();
        
    Matrix::Transpose(r.WorldXform, m_cbPerDraw.Data);    
    m_cbPerDraw.Update(dc);
        
    uint32_t stride = r.mesh->vertexBuffer->GetStride();
    uint32_t offset = 0;
    uint32_t startIndex = 0;
    uint32_t startVertex = 0;
    uint32_t indexCount = r.mesh->indexBuffer->GetCount();
    ID3D11Buffer* d3dvb = r.mesh->vertexBuffer->GetBuffer();
    ID3D11Buffer* d3dib = r.mesh->indexBuffer->GetBuffer();

    dc->IASetPrimitiveTopology( (D3D11_PRIMITIVE_TOPOLOGY)r.mesh->primitiveType );
    dc->IASetVertexBuffers( 0, 1, &d3dvb, &stride, &offset );
    dc->IASetIndexBuffer(d3dib, (DXGI_FORMAT) r.mesh->indexBuffer->GetFormat(), 0);

    dc->DrawIndexed(indexCount, startIndex, startVertex);
}
Exemple #25
0
void D11State::blit(unsigned int x, unsigned int y, unsigned int w, unsigned int h) {
	HRESULT hr;

	ods("D3D11: Blit %d %d %d %d", x, y, w, h);

	if (! pTexture || ! pSRView || uiLeft == uiRight)
		return;

	D3D11_MAPPED_SUBRESOURCE mappedTex;
	hr = pDeviceContext->Map(pTexture, D3D11CalcSubresource(0, 0, 1), D3D11_MAP_WRITE_DISCARD, 0, &mappedTex);
	if (FAILED(hr)) {
		ods("D3D11: Failed map");
	}

	UCHAR* pTexels = (UCHAR*)mappedTex.pData;

	for (unsigned int r=0;r< uiHeight; ++r) {
		unsigned char *sptr = a_ucTexture + r * uiWidth * 4;
		unsigned char *dptr = reinterpret_cast<unsigned char *>(pTexels) + r * mappedTex.RowPitch;
		memcpy(dptr, sptr, uiWidth * 4);
	}

	pDeviceContext->Unmap(pTexture, D3D11CalcSubresource(0, 0, 1));
}
Exemple #26
0
	//----------------------------------------------------------------------------------------------------
	bool EEPoints2D::Update()
	{
		if (!EEObject::Update())
			return false;

		UpdateObjectState();

		if (m_isPositionDirty)
		{
			m_isPositionDirty = false;
		}

		if (m_isScaleDirty || m_isLocalZOrderDirty || m_isPointsDirty)
		{
			std::vector<EEPoints2DVertex> vertices(m_points.size());
			for (unsigned int i = 0; i < m_points.size(); ++i)
			{
				vertices[i].pos = FLOAT3(m_points[i], m_localZOrder * 0.0001f);
			}

			if (m_isPointsDirty)
				CreatePointsVertexBuffer();
			ID3D11DeviceContext *deviceContext = EECore::s_EECore->GetDeviceContext();
			D3D11_MAPPED_SUBRESOURCE mappedResource;
			ZeroMemory(&mappedResource, sizeof(D3D11_MAPPED_SUBRESOURCE));
			deviceContext->Map(m_pointsVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
			memcpy(mappedResource.pData, &vertices[0], vertices.size() * sizeof(EEPoints2DVertex));
			deviceContext->Unmap(m_pointsVB, 0);

			m_isScaleDirty = false;
			m_isLocalZOrderDirty = false;
			m_isPointsDirty = false;
		}

		return true;
	}
Exemple #27
0
HRESULT Image11::map(D3D11_MAP mapType, D3D11_MAPPED_SUBRESOURCE *map)
{
    createStagingTexture();

    HRESULT result = E_FAIL;

    if (mStagingTexture)
    {
        ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
        result = deviceContext->Map(mStagingTexture, mStagingSubresource, mapType, 0, map);

        // this can fail if the device is removed (from TDR)
        if (d3d11::isDeviceLostError(result))
        {
            mRenderer->notifyDeviceLost();
        }
        else if (SUCCEEDED(result))
        {
            mDirty = true;
        }
    }

    return result;
}
bool IndexBuffer11::discard()
{
    if (mBuffer)
    {
        ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();

        D3D11_MAPPED_SUBRESOURCE mappedResource;
        HRESULT result = dxContext->Map(mBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
        if (FAILED(result))
        {
            ERR("Index buffer map failed with error 0x%08x", result);
            return false;
        }

        dxContext->Unmap(mBuffer, 0);

        return true;
    }
    else
    {
        ERR("Index buffer not initialized.");
        return false;
    }
}
Exemple #29
0
void Terrain::DrawShadowMap(const Camera& cam)
{
	ID3D11DeviceContext* dc = pDeviceContext;

	dc->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST);
	dc->IASetInputLayout(InputLayouts::Terrain);

	UINT stride = sizeof(Vertex::Terrain);
    UINT offset = 0;

    dc->IASetVertexBuffers(0, 1, &mQuadPatchVB, &stride, &offset);
	dc->IASetIndexBuffer(mQuadPatchIB, DXGI_FORMAT_R16_UINT, 0);

	XMMATRIX view = XMLoadFloat4x4(&d3d->m_LightView);
	XMMATRIX proj = XMLoadFloat4x4(&d3d->m_LightProj);
	XMMATRIX viewProj = XMMatrixMultiply(view, proj);
	XMMATRIX world  = XMLoadFloat4x4(&mWorld);
	XMMATRIX worldInvTranspose = MathHelper::InverseTranspose(world);
	XMMATRIX worldViewProj = world*viewProj;
	XMMATRIX ShadowTransform = world * XMLoadFloat4x4(&d3d->m_ShadowTransform);
	XMFLOAT4 worldPlanes[6];
	ExtractFrustumPlanes(worldPlanes, cam.ViewProj());

	// Set per frame constants.
	
	Effects::TerrainFX->SetViewProj(viewProj);
	Effects::TerrainFX->SetEyePosW(cam.GetPosition());
	Effects::TerrainFX->SetMinDist(20.0f);
	Effects::TerrainFX->SetMaxDist(400.0f);
	Effects::TerrainFX->SetMinTess(0.0f);
	Effects::TerrainFX->SetMaxTess(3.0f);
	Effects::TerrainFX->SetTexelCellSpaceU(1.0f / mInfo.HeightmapWidth);
	Effects::TerrainFX->SetTexelCellSpaceV(1.0f / mInfo.HeightmapHeight);
	Effects::TerrainFX->SetWorldCellSpace(mInfo.CellSpacing);
	Effects::TerrainFX->SetWorldFrustumPlanes(worldPlanes);

	Effects::TerrainFX->SetHeightMap(mHeightMapSRV);
	Effects::TerrainFX->SetShadowMap(d3d->GetShadowMap());
	Effects::TerrainFX->SetShadowTransform(ShadowTransform);

	ID3DX11EffectTechnique* tech = Effects::TerrainFX->TessBuildShadowMapTech;
    D3DX11_TECHNIQUE_DESC techDesc;
    tech->GetDesc( &techDesc );

    for(UINT i = 0; i < techDesc.Passes; ++i)
    {
        ID3DX11EffectPass* pass = tech->GetPassByIndex(i);
		pass->Apply(0, dc);

		dc->DrawIndexed(mNumPatchQuadFaces*4, 0, 0);
	}	
	
	//dc->HSSetShader(0, 0, 0);
	//dc->DSSetShader(0, 0, 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()