Esempio n. 1
0
// Set the render state before drawing this object
//-----------------------------------------------------------------------------
void CPUTModelDX11::UpdateShaderConstants(CPUTRenderParameters &renderParams)
{
    ID3D11DeviceContext *pContext  = ((CPUTRenderParametersDX*)&renderParams)->mpContext;
    D3D11_MAPPED_SUBRESOURCE mapInfo;
    pContext->Map( mpModelConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapInfo );
    {
        CPUTModelConstantBuffer *pCb = (CPUTModelConstantBuffer*)mapInfo.pData;

        // TODO: remove construction of XMM type
        XMMATRIX     world((float*)GetWorldMatrix());
        pCb->World = world;

        CPUTCamera *pCamera   = renderParams.mpCamera;
        XMVECTOR    cameraPos = XMLoadFloat3(&XMFLOAT3( 0.0f, 0.0f, 0.0f ));
        if( pCamera )
        {
            XMMATRIX    view((float*)pCamera->GetViewMatrix());
            XMMATRIX    projection((float*)pCamera->GetProjectionMatrix());
            float      *pCameraPos = (float*)&pCamera->GetPosition();
            cameraPos = XMLoadFloat3(&XMFLOAT3( pCameraPos[0], pCameraPos[1], pCameraPos[2] ));

            // Note: We compute viewProjection to a local to avoid reading from write-combined memory.
            // The constant buffer uses write-combined memory.  We read this matrix when computing WorldViewProjection.
            // It is very slow to read it directly from the constant buffer.
            XMMATRIX viewProjection  = view * projection;
            pCb->ViewProjection      = viewProjection;
            pCb->WorldViewProjection = world * viewProjection;
            XMVECTOR determinant     = XMMatrixDeterminant(world);
            pCb->InverseWorld        = XMMatrixInverse(&determinant, XMMatrixTranspose(world));
        }
        // TODO: Have the lights set their render states?

        XMVECTOR lightDirection = XMLoadFloat3(&XMFLOAT3( gLightDir.x, gLightDir.y, gLightDir.z ));
        pCb->LightDirection     = XMVector3Normalize(lightDirection);
        pCb->EyePosition        = cameraPos;
        float *bbCWS = (float*)&mBoundingBoxCenterWorldSpace;
        float *bbHWS = (float*)&mBoundingBoxHalfWorldSpace;
        float *bbCOS = (float*)&mBoundingBoxCenterObjectSpace;
        float *bbHOS = (float*)&mBoundingBoxHalfObjectSpace;
        pCb->BoundingBoxCenterWorldSpace  = XMLoadFloat3(&XMFLOAT3( bbCWS[0], bbCWS[1], bbCWS[2] ));
        pCb->BoundingBoxHalfWorldSpace    = XMLoadFloat3(&XMFLOAT3( bbHWS[0], bbHWS[1], bbHWS[2] ));
        pCb->BoundingBoxCenterObjectSpace = XMLoadFloat3(&XMFLOAT3( bbCOS[0], bbCOS[1], bbCOS[2] ));
        pCb->BoundingBoxHalfObjectSpace   = XMLoadFloat3(&XMFLOAT3( bbHOS[0], bbHOS[1], bbHOS[2] ));

        // Shadow camera
        XMMATRIX    shadowView, shadowProjection;
        CPUTCamera *pShadowCamera = gpSample->GetShadowCamera();
        if( pShadowCamera )
        {
            shadowView = XMMATRIX((float*)pShadowCamera->GetViewMatrix());
            shadowProjection = XMMATRIX((float*)pShadowCamera->GetProjectionMatrix());
            pCb->LightWorldViewProjection = world * shadowView * shadowProjection;
        }
    }
    pContext->Unmap(mpModelConstantBuffer,0);
}
Esempio n. 2
0
void VertexBuffer11::hintUnmapResource()
{
    if (mMappedResourceData != NULL)
    {
        ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();
        dxContext->Unmap(mBuffer, 0);

        mMappedResourceData = NULL;
    }
}
Esempio n. 3
0
gl::Error IndexBuffer11::unmapBuffer()
{
    if (!mBuffer)
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Internal index buffer is not initialized.");
    }

    ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();
    dxContext->Unmap(mBuffer, 0);
    return gl::Error(GL_NO_ERROR);
}
Esempio n. 4
0
	//----------------------------------------------------------------------------------------------------
	bool EECurve2D::Update()
	{
		if (!EEObject::Update())
			return false;

		UpdateObjectState();

		if (m_isPositionDirty)
		{
			m_isPositionDirty = false;
		}

		if (m_isLocalZOrderDirty || m_isCurveDirty)
		{
			std::vector<EECurve2DVertex> vertices(m_curve.size() << 1);
			if (m_curve.size() > 1)
			{
				float halfWidth = m_width / 2;
				float deltaTex = 1.f / m_curve.size();
				for (unsigned int i = 0; i < m_curve.size() - 1; ++i)
				{
					int index = i << 1;
					FLOAT2 vertical = (m_curve[i + 1] - m_curve[i]).GetVertical();
					vertices[index].pos = FLOAT3(m_curve[i] + vertical * halfWidth, m_localZOrder * 0.0001f);
					vertices[index].tex = FLOAT2(m_texRect.x, m_texRect.y + i * deltaTex);
					vertices[index + 1].pos = FLOAT3(m_curve[i] - vertical * halfWidth, m_localZOrder * 0.0001f);
					vertices[index + 1].tex = FLOAT2(m_texRect.z, m_texRect.y + i * deltaTex);
				}
				FLOAT2 vertical = (m_curve[m_curve.size() - 1] - m_curve[m_curve.size() - 2]).GetVertical();
				vertices[vertices.size() - 2].pos = FLOAT3(m_curve.back() + vertical * halfWidth, m_localZOrder * 0.0001f);
				vertices[vertices.size() - 2].tex = FLOAT2(m_texRect.x, m_texRect.w);
				vertices[vertices.size() - 1].pos = FLOAT3(m_curve.back() - vertical * halfWidth, m_localZOrder * 0.0001f);
				vertices[vertices.size() - 1].tex = FLOAT2(m_texRect.z, m_texRect.w);
			}

			if (m_isCurveDirty)
				CreateCurveVertexBuffer();
			if (m_curveVB)
			{
				ID3D11DeviceContext *deviceContext = EECore::s_EECore->GetDeviceContext();
				D3D11_MAPPED_SUBRESOURCE mappedResource;
				ZeroMemory(&mappedResource, sizeof(D3D11_MAPPED_SUBRESOURCE));
				deviceContext->Map(m_curveVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
				memcpy(mappedResource.pData, &vertices[0], sizeof(EECurve2DVertex)* vertices.size());
				deviceContext->Unmap(m_curveVB, 0);
			}

			m_isLocalZOrderDirty = false;
			m_isCurveDirty = false;
		}

		return true;
	}
void ShadingComputeShader::setParameters( ID3D11DeviceContext& deviceContext, const float3& cameraPos,
                                          const std::shared_ptr< Texture2DSpecBind< TexBind::ShaderResource, float4 > > positionTexture,
                                          const std::shared_ptr< Texture2DSpecBind< TexBind::ShaderResource, uchar4 > > albedoTexture, 
                                          const std::shared_ptr< Texture2DSpecBind< TexBind::ShaderResource, unsigned char > > metalnessTexture, 
                                          const std::shared_ptr< Texture2DSpecBind< TexBind::ShaderResource, unsigned char > > roughnessTexture, 
                                          const std::shared_ptr< Texture2DSpecBind< TexBind::ShaderResource, float4 > > normalTexture,
										  const std::shared_ptr< Texture2DSpecBind< TexBind::ShaderResource, unsigned char > > illuminationTexture,
									      const Light& light )
{
    if ( !m_compiled ) 
        throw std::exception( "ShadingComputeShader::setParameters - Shader hasn't been compiled yet." );

    { // Set input buffers and textures.
        const unsigned int resourceCount = 6;
        ID3D11ShaderResourceView* resources[ resourceCount ] = { 
            positionTexture->getShaderResourceView(),
            albedoTexture->getShaderResourceView(),
            metalnessTexture->getShaderResourceView(),
            roughnessTexture->getShaderResourceView(),
            normalTexture->getShaderResourceView(),
			illuminationTexture->getShaderResourceView()
        };

        deviceContext.CSSetShaderResources( 0, resourceCount, resources );
    }

    { // Set constant buffer.
        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( "ShadingComputeShader::setParameters - mapping constant buffer to CPU memory failed." );

        dataPtr = (ConstantBuffer*)mappedResource.pData;

        dataPtr->cameraPos         = cameraPos;
        dataPtr->pad1		       = 0.0f;
        dataPtr->lightPosition     = float4( light.getPosition(), 0.0f );
        dataPtr->lightColor        = float4( light.getColor(), 0.0f );
        dataPtr->outputTextureSize = float2( (float)positionTexture->getWidth(), (float)positionTexture->getHeight() ); // #TODO: Size should be taken from real output texture, not one of inputs (right now, we are assuming they have the same size).

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

        deviceContext.CSSetConstantBuffers( 0, 1, m_constantInputBuffer.GetAddressOf() );
    }

    { // Set texture sampler.
        ID3D11SamplerState* samplers[] = { m_linearSamplerState.Get(), m_pointSamplerState.Get() };
        deviceContext.CSSetSamplers( 0, 2, samplers );
    }
}
Esempio n. 6
0
bool VertexBuffer11::storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count,
                                           GLsizei instances, unsigned int offset)
{
    if (mBuffer)
    {
        gl::Buffer *buffer = attrib.mBoundBuffer.get();

        int inputStride = attrib.stride();
        const VertexConverter &converter = getVertexConversion(attrib);

        ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();

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

        char* output = reinterpret_cast<char*>(mappedResource.pData) + offset;

        const char *input = NULL;
        if (buffer)
        {
            BufferStorage *storage = buffer->getStorage();
            input = static_cast<const char*>(storage->getData()) + static_cast<int>(attrib.mOffset);
        }
        else
        {
            input = static_cast<const char*>(attrib.mPointer);
        }

        if (instances == 0 || attrib.mDivisor == 0)
        {
            input += inputStride * start;
        }

        converter.conversionFunc(input, inputStride, count, output);

        dxContext->Unmap(mBuffer, 0);

        return true;
    }
    else
    {
        ERR("Vertex buffer not initialized.");
        return false;
    }
}
Esempio n. 7
0
bool IndexBuffer11::unmapBuffer()
{
    if (mBuffer)
    {
        ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();
        dxContext->Unmap(mBuffer, 0);
        return true;
    }
    else
    {
        ERR("Index buffer not initialized.");
        return false;
    }
}
Esempio n. 8
0
void SpriteShader::SetParameters()
{
	D3D11_MAPPED_SUBRESOURCE ms0, ms1;
	ID3D11DeviceContext* devcon = (ID3D11DeviceContext*)EngineCore::GetGraphicsAPI()->GetDeviceContext();

	// Set buffer 0
	devcon->Map(
		gpu_vs_buffer0,
		0,
		D3D11_MAP_WRITE_DISCARD,
		0,
		&ms0
	);

	memcpy(ms0.pData, &cpu_vs_buffer0, sizeof(cpu_vs_buffer0));
	devcon->Unmap(gpu_vs_buffer0, 0);
	devcon->VSSetConstantBuffers(0, 1, &gpu_vs_buffer0);

	// Set buffer 1
	devcon->Map(
		gpu_vs_buffer1,
		0,
		D3D11_MAP_WRITE_DISCARD,
		0,
		&ms1
	);

	memcpy(ms1.pData, &cpu_vs_buffer1, sizeof(cpu_vs_buffer1));
	devcon->Unmap(gpu_vs_buffer1, 0);
	devcon->VSSetConstantBuffers(1, 1, &gpu_vs_buffer1);

	PNG_Texture* png_tex = (PNG_Texture*)texture;
	ID3D11ShaderResourceView* srv = png_tex->GetShaderResourceView();
	devcon->PSSetShaderResources(0, 1, &srv);

	devcon->PSSetSamplers(0, 1, &samplerState);
}
void GenerateRefractedRaysComputeShader::setParameters( ID3D11DeviceContext& deviceContext, const unsigned int refractionLevel,
                                                        const Texture2DSpecBind< TexBind::ShaderResource, float4 >& rayDirectionTexture,
                                                        const Texture2DSpecBind< TexBind::ShaderResource, float4 >& rayHitPositionTexture,
                                                        const Texture2DSpecBind< TexBind::ShaderResource, float4 >& rayHitNormalTexture,
                                                        const Texture2DSpecBind< TexBind::ShaderResource, unsigned char >& rayHitRoughnessTexture,
                                                        const Texture2DSpecBind< TexBind::ShaderResource, unsigned char >& rayHitRefractiveIndexTexture,
                                                        const Texture2DSpecBind< TexBind::ShaderResource, uchar4 >& contributionTermTexture,
                                                        const std::shared_ptr< Texture2DSpecBind< TexBind::ShaderResource, unsigned char > > prevRefractiveIndexTexture, // Only makes sense for refraction level >= 2.
                                                        const std::shared_ptr< const Texture2DSpecBind< TexBind::ShaderResource, unsigned char > > currentRefractiveIndexTexture,
                                                        const int outputTextureWidth, const int outputTextureHeight )
{
    if ( !m_compiled ) throw std::exception( "GenerateRefractedRaysComputeShader::setParameters - Shader hasn't been compiled yet." );

    { // Set input buffers and textures.
        m_resourceCount = 8;
        std::vector< ID3D11ShaderResourceView* > resources;
        resources.reserve( m_resourceCount );

        resources.push_back( rayDirectionTexture.getShaderResourceView() );
        resources.push_back( rayHitPositionTexture.getShaderResourceView() );
        resources.push_back( rayHitNormalTexture.getShaderResourceView() );
        resources.push_back( rayHitRoughnessTexture.getShaderResourceView() );
        resources.push_back( rayHitRefractiveIndexTexture.getShaderResourceView() );
        resources.push_back( contributionTermTexture.getShaderResourceView() );

        resources.push_back( prevRefractiveIndexTexture ? prevRefractiveIndexTexture->getShaderResourceView() : nullptr );
        resources.push_back( currentRefractiveIndexTexture ? currentRefractiveIndexTexture->getShaderResourceView() : nullptr );

        deviceContext.CSSetShaderResources( 0, m_resourceCount, resources.data() );
    }

    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( "GenerateRefractedRaysComputeShader::setParameters - mapping constant buffer to CPU memory failed." );

    dataPtr = (ConstantBuffer*)mappedResource.pData;

    dataPtr->refractionLevel   = refractionLevel;
    dataPtr->outputTextureSize = float2( (float)outputTextureWidth, (float)outputTextureHeight );

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

    deviceContext.CSSetConstantBuffers( 0, 1, m_constantInputBuffer.GetAddressOf() );

    ID3D11SamplerState* samplerStates[] = { m_samplerStateLinearFilter.Get() };
    deviceContext.CSSetSamplers( 0, 1, samplerStates );
}
Esempio n. 10
0
Grid::Grid(UINT n)
	: n(n)
{
	ID3D11DeviceContext* devcon = (ID3D11DeviceContext*)EngineCore::GetGraphicsAPI()->GetDeviceContext();
	ID3D11Device* dev = (ID3D11Device*)EngineCore::GetGraphicsAPI()->GetDevice();
	
	D3D11_BUFFER_DESC bd;
	ZeroMemory(&bd, sizeof(bd));

	UINT cntV = 2 * (2 * n + 1);
	UINT size = cntV * sizeof(Vertex);

	bd.Usage = D3D11_USAGE_DYNAMIC;
	bd.ByteWidth = size;
	bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	
	dev->CreateBuffer(
		&bd,
		NULL,
		&buff
	);

	D3D11_MAPPED_SUBRESOURCE ms;
	devcon->Map(
		buff,
		NULL,
		D3D11_MAP_WRITE_DISCARD,
		NULL,
		&ms
	);

	vector<Vertex> cpu_buff;
	float currX = -(float)n;
	for (UINT i = 0; i < cntV / 2; ++i)
	{
		cpu_buff.push_back(Vertex(XMFLOAT3(currX, (float)n, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)));
		cpu_buff.push_back(Vertex(XMFLOAT3(currX, -(float)n, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)));
		currX += 1.0f;
	}

	
	cpu_buff[cntV / 2 - (cntV / 2) % 2].color = XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f);
	cpu_buff[cntV / 2 + !((cntV / 2) % 2)].color = XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f);

	memcpy(ms.pData, cpu_buff.data(), size);

	devcon->Unmap(buff, 0);
}
Esempio n. 11
0
		void D3D11Texture::unmap()
		{
			ID3D11DeviceContext *ctx = static_cast<D3D11RenderSystem*>(D3D11RenderSystem::getPtr())->getContext();

			switch (mDimension)
			{
			case D3D11_SRV_DIMENSION_TEXTURE2D:

				ID3D11Texture2D *tex;
				mTexture->GetResource((ID3D11Resource**)&tex);

				ctx->Unmap(tex, D3D11CalcSubresource(0,0,1));

				SAFE_RELEASE(tex);
			}
		}
Esempio n. 12
0
Void D3D11TextureCube::UnLock( const D3D11SubResourceIndex * pIndex, D3D11TextureCubeFace iFace, D3D11DeferredContext * pContext )
{
    DebugAssert( IsCreated() );
    DebugAssert( CanLock() );
    DebugAssert( m_bLocked );

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

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

    pDeviceContext->Unmap( m_pTexture, iSubResource );

    m_bLocked = false;
}
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);
}
Esempio n. 14
0
void CD3DTexture::SaveTexture()
{
  if (m_texture)
  {
    delete[] m_data;
    m_data = nullptr;

    ID3D11DeviceContext* pContext = g_Windowing.GetImmediateContext();

    D3D11_TEXTURE2D_DESC textureDesc;
    m_texture->GetDesc(&textureDesc);

    ID3D11Texture2D* texture = nullptr;
    if (textureDesc.Usage != D3D11_USAGE_STAGING || 0 == (textureDesc.CPUAccessFlags & D3D11_CPU_ACCESS_READ))
    {
      // create texture which can be readed by CPU - D3D11_USAGE_STAGING
      CD3D11_TEXTURE2D_DESC stagingDesc(textureDesc);
      stagingDesc.Usage = D3D11_USAGE_STAGING;
      stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
      stagingDesc.BindFlags = 0;

      if (FAILED(g_Windowing.Get3D11Device()->CreateTexture2D(&stagingDesc, NULL, &texture)))
        return;

      // copy contents to new texture
      pContext->CopyResource(texture, m_texture);
    }
    else 
      texture = m_texture;

    // read data from texture
    D3D11_MAPPED_SUBRESOURCE res;
    if (SUCCEEDED(pContext->Map(texture, 0, D3D11_MAP_READ, 0, &res)))
    {
      m_pitch = res.RowPitch;
      unsigned int memUsage = GetMemoryUsage(res.RowPitch);
      m_data = new unsigned char[memUsage];
      memcpy(m_data, res.pData, memUsage);
      pContext->Unmap(texture, 0);
    }
    else
      CLog::Log(LOGERROR, "%s - Failed to store resource.", __FUNCTION__);

    if (texture != m_texture)
      SAFE_RELEASE(texture);
  }
}
Esempio n. 15
0
	//----------------------------------------------------------------------------------------------------
	bool EEQuad2D::Update()
	{
		if (!EEObject::Update())
			return false;

		UpdateObjectState();

		if (m_isPositionDirty)
		{
			m_isPositionDirty = false;
		}

		if (m_isScaleDirty || m_isLocalZOrderDirty || m_isTexRectDirty)
		{
			Rect_Float rect(
				-m_quadWidth / 2,
				-m_quadHeight / 2,
				m_quadWidth / 2,
				m_quadHeight / 2
				);

			EEQuad2DVertex quadVertices[4];
			quadVertices[0].pos = FLOAT3(rect.x, rect.y, m_localZOrder * 0.0001f);
			quadVertices[0].tex = FLOAT2(m_texRect.x, m_texRect.y);
			quadVertices[1].pos = FLOAT3(rect.z, rect.y, m_localZOrder * 0.0001f);
			quadVertices[1].tex = FLOAT2(m_texRect.z, m_texRect.y);
			quadVertices[2].pos = FLOAT3(rect.x, rect.w, m_localZOrder * 0.0001f);
			quadVertices[2].tex = FLOAT2(m_texRect.x, m_texRect.w);
			quadVertices[3].pos = FLOAT3(rect.z, rect.w, m_localZOrder * 0.0001f);
			quadVertices[3].tex = FLOAT2(m_texRect.z, m_texRect.w);

			ID3D11DeviceContext *deviceContext = EECore::s_EECore->GetDeviceContext();
			D3D11_MAPPED_SUBRESOURCE mappedResource;
			ZeroMemory(&mappedResource, sizeof(D3D11_MAPPED_SUBRESOURCE));
			deviceContext->Map(m_quadVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
			memcpy(mappedResource.pData, quadVertices, sizeof(quadVertices));
			deviceContext->Unmap(m_quadVB, 0);

			m_isScaleDirty = false;
			m_isLocalZOrderDirty = false;
			m_isTexRectDirty = false;
		}

		return true;
	}
Esempio n. 16
0
void CD3DBuffer::OnDestroyDevice(bool fatal)
{
  if (fatal)
  {
    SAFE_RELEASE(m_buffer);
    return;
  }

  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 (SUCCEEDED(pDevice->CreateBuffer(&trgDesc, NULL, &buffer)))
      pContext->CopyResource(buffer, m_buffer);
  }
  else
    buffer = m_buffer;

  if (buffer != nullptr)
  {
    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);
}
Esempio n. 17
0
void LineMesh::UpdateBuffer(ID3D11Device* device)
{
  ID3D11DeviceContext* context;
  device->GetImmediateContext(&context);

  // Update VERTEX BUFFER
  D3D11_MAPPED_SUBRESOURCE mappedResource;
  HR(context->Map(mVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

  // Get a pointer to the data in the vertex buffer.
  LineVertex* verticesPtr = (LineVertex*)mappedResource.pData;

  // Copy the data into the vertex buffer.
  memcpy(verticesPtr, (void*)mLineVertices.data(), (sizeof(LineVertex) * mLineVertices.size()));

  // Unlock the vertex buffer.
  context->Unmap(mVertexBuffer, 0);
}
Esempio n. 18
0
void DirectionalLightShader::Setup(DirectionalLight * light)
{
	ID3D11DeviceContext* context = gCore.GetContext();

	D3D11_MAPPED_SUBRESOURCE mr;
	if (SUCCEEDED(context->Map(mCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mr)))
	{
		CBLight* dst = (CBLight*)mr.pData;
		Color2Vector3(light->GetColor(), dst->color);
		dst->dir = light->GetTransform().position;
		dst->att = light->GetIntensity();
		light->GetVP(dst->vp);
		context->Unmap(mCB, 0);
	}

	context->PSSetConstantBuffers(1, 1, &mCB);
	context->PSSetShader(mPS, nullptr, 0);
}
Esempio n. 19
0
    void ActorPicker::PostRender(void)
    {
        //todo: move to renderer
        D3D11_MAPPED_SUBRESOURCE res;
        ID3D11DeviceContext* ctx = (ID3D11DeviceContext*)CmGetApp()->VGetRenderer()->VGetContext();
        ID3D11Resource* dst = (ID3D11Resource*)m_pTexture->VGetDevicePtr();
        ID3D11Resource* src = (ID3D11Resource*)m_pRenderTarget->VGetTexture()->VGetDevicePtr();

        ctx->CopyResource(dst, src);
        D3D_SAVE_CALL(ctx->Map(dst, 0, D3D11_MAP_READ, 0, &res));
        m_currentActor = ((uint*)(res.pData))[0];
        ctx->Unmap(dst, 0);

        IConstShaderBuffer* buffer = CmGetApp()->VGetHumanView()->VGetRenderer()->VGetConstShaderBuffer(chimera::eSelectedActorIdBuffer);
        uint* b = (uint*)buffer->VMap();
        b[0] = m_currentActor;
        buffer->VUnmap();
    }
Esempio n. 20
0
void BufferStorage11::setData(const void* data, size_t size, size_t offset)
{
    size_t requiredSize = size + offset;
    mSize = std::max(mSize, requiredSize);

    if (data)
    {
        NativeBuffer11 *stagingBuffer = getStagingBuffer();

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

        // Explicitly resize the staging buffer, preserving data if the new data will not
        // completely fill the buffer
        if (stagingBuffer->getSize() < requiredSize)
        {
            bool preserveData = (offset > 0);
            if (!stagingBuffer->resize(requiredSize, preserveData))
            {
                // Out-of-memory
                return;
            }
        }

        ID3D11DeviceContext *context = mRenderer->getDeviceContext();

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

        unsigned char *offsetBufferPointer = reinterpret_cast<unsigned char *>(mappedResource.pData) + offset;
        memcpy(offsetBufferPointer, data, size);

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

        stagingBuffer->setDataRevision(stagingBuffer->getDataRevision() + 1);
    }
}
void SkeletonModelVertexShader::setParameters( ID3D11DeviceContext& deviceContext, const float43& worldMatrix, const float44& viewMatrix, const float44& projectionMatrix, const SkeletonMesh& skeletonMesh, const SkeletonPose& bonesPoseInSkeletonSpace )
{
	if ( !m_compiled ) throw std::exception( "SkeletonModelVertexShader::setParameters - Shader hasn't been compiled yet." );
	if ( skeletonMesh.getBoneCount( ) != bonesPoseInSkeletonSpace.getBonesCount( ) ) throw std::exception( "SkeletonModelVertexShader::setParameters - there is different number of bones in bind pose and current pose." );
	if ( skeletonMesh.getBoneCount( ) > maxBoneCount ) throw std::exception( "SkeletonModelVertexShader::setParameters - the number of bones in the mesh exceeds the shader limit." );
	if ( skeletonMesh.getBonesPerVertexCount( ) == BonesPerVertexCount::Type::ZERO ) throw std::exception( "SkeletonModelVertexShader::setParameters - mesh's number-of-bones-per-vertex is ZERO. Should be one of the supported positive values." );

	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( "SkeletonModelVertexShader::setParameters - mapping shader's constant input buffer to RAM memory failed" );

	dataPtr = (ConstantBuffer*)mappedResource.pData;

	{ // Fill constant buffer.
		dataPtr->world = float44( worldMatrix ).getTranspose();
		dataPtr->view = viewMatrix.getTranspose();
		dataPtr->projection = projectionMatrix.getTranspose();

		const unsigned char boneCount = skeletonMesh.getBoneCount();
		for ( unsigned char boneIndex = 1; boneIndex <= boneCount; ++boneIndex ) {
			dataPtr->bonesBindPose[ boneIndex - 1 ]    = float44( skeletonMesh.getBone( boneIndex ).getBindPose() ).getTranspose();
			dataPtr->bonesBindPoseInv[ boneIndex - 1 ] = float44( skeletonMesh.getBone( boneIndex ).getBindPoseInv() ).getTranspose();
			dataPtr->bonesPose[ boneIndex - 1 ]        = float44( bonesPoseInSkeletonSpace.getBonePose( boneIndex ) ).getTranspose( );
		}

		// Set unused bones' pose to identity.
		for ( unsigned char i = boneCount; i < maxBoneCount; ++i ) {
			dataPtr->bonesBindPose[ i ].identity();
			dataPtr->bonesBindPoseInv[ i ].identity();
			dataPtr->bonesPose[ i ].identity();
		}

		dataPtr->bonesPerVertex = static_cast<unsigned char>( skeletonMesh.getBonesPerVertexCount() );
	}

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

	deviceContext.VSSetConstantBuffers( 0, 1, m_constantInputBuffer.GetAddressOf() );

	// Save currently configured bones-per-vertex-count.
	m_bonesPerVertexCurrentConfig = skeletonMesh.getBonesPerVertexCount();
}
Esempio n. 22
0
void D11State::setRect() {
	HRESULT hr;

	ods("D3D11: SetRect");

	float w = static_cast<float>(uiWidth);
	float h = static_cast<float>(uiHeight);

	float left   = static_cast<float>(uiLeft) - 0.5f;
	float top    = static_cast<float>(uiTop) - 0.5f;
	float right  = static_cast<float>(uiRight) + 0.5f;
	float bottom = static_cast<float>(uiBottom) + 0.5f;

	float texl = (left) / w;
	float text = (top) / h;
	float texr = (right + 1.0f) / w;
	float texb = (bottom + 1.0f) / h;

	left = 2.0f * (left / vp.Width) - 1.0f;
	right = 2.0f * (right / vp.Width) - 1.0f;
	top = -2.0f * (top / vp.Height) + 1.0f;
	bottom = -2.0f * (bottom / vp.Height) + 1.0f;

	ods("D3D11: Vertex (%f %f) (%f %f)", left, top, right, bottom);

	// Create vertex buffer
	SimpleVertex vertices[] = {
		{ SimpleVec3(left, top, 0.5f), SimpleVec2(texl, text) },
		{ SimpleVec3(right, top, 0.5f), SimpleVec2(texr, text) },
		{ SimpleVec3(right, bottom, 0.5f), SimpleVec2(texr, texb) },
		{ SimpleVec3(left, bottom, 0.5f), SimpleVec2(texl, texb) },
	};

	// map/unmap to temporarily deny GPU access to the resource pVertexBuffer
	D3D11_MAPPED_SUBRESOURCE res;
	hr = pDeviceContext->Map(pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &res);

	const int verticesSize = sizeof(vertices);
	static_assert(verticesSize == VERTEXBUFFER_SIZE, "The vertex buffer size differs from the locally created vertex buffer.");
	memcpy(res.pData, vertices, verticesSize);
	ods("D3D11: Map: %lx %d", hr, sizeof(vertices));
	pDeviceContext->Unmap(pVertexBuffer, 0);
}
Esempio n. 23
0
//==================================================================================================================================
void HDR::UpdateContantBuffer(int mipLevel0, int mipLevel1, unsigned int width, unsigned int height)
{
	ID3D11DeviceContext* context = mD3DSystem->GetDeviceContext();
	
	cbConstants cConst;
	cConst.width = width;
	cConst.height = height;
	cConst.mipLevel0 = mipLevel0;
	cConst.mipLevel1 = mipLevel1;
	D3D11_MAPPED_SUBRESOURCE mapped_res;
	context->Map(m_pCSConstants, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_res);
	{
		assert(mapped_res.pData);
		*(cbConstants*)mapped_res.pData = cConst;
	}
	context->Unmap(m_pCSConstants, 0);
	
	context->CSSetConstantBuffers(1, 1, &m_pCSConstants);
}
Esempio n. 24
0
//==================================================================================================================================
void HDR::UpdateBloomConstants(float middleGrey, float bloomThreshold, float bloomMultiplier)
{
	ID3D11DeviceContext* context = mD3DSystem->GetDeviceContext();
	
	cbBloomConstants cBC;
	cBC.g_MiddleGrey = middleGrey;
	cBC.g_BloomThreshold = bloomThreshold;
	cBC.g_BloomMultiplier = bloomMultiplier;
	cBC.padding = 0;
	D3D11_MAPPED_SUBRESOURCE mapped_res;
	context->Map(m_pBloomConstants, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_res);
	{
		assert(mapped_res.pData);
		*(cbBloomConstants*)mapped_res.pData = cBC;
	}
	context->Unmap(m_pBloomConstants, 0);
	
	context->CSSetConstantBuffers(2, 1, &m_pBloomConstants);
	context->PSSetConstantBuffers(2, 1, &m_pBloomConstants);
}
Esempio n. 25
0
gl::Error VertexBuffer11::discard()
{
    if (!mBuffer)
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Internal vertex buffer is not initialized.");
    }

    ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();

    D3D11_MAPPED_SUBRESOURCE mappedResource;
    HRESULT result = dxContext->Map(mBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
    if (FAILED(result))
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Failed to map internal buffer for discarding, HRESULT: 0x%08x", result);
    }

    dxContext->Unmap(mBuffer, 0);

    return gl::Error(GL_NO_ERROR);
}
void BlockModelVertexShader::setParameters( ID3D11DeviceContext& deviceContext, const float43& worldMatrix, const float44& viewMatrix, const float44& projectionMatrix ) {
	if ( !m_compiled ) throw std::exception( "BlockModelVertexShader::setParameters - Shader hasn't been compiled yet" );

	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;

	// Transpose from row-major to column-major to fit each column in one register.
	dataPtr->world = float44( worldMatrix ).getTranspose();
	dataPtr->view = viewMatrix.getTranspose();
	dataPtr->projection = projectionMatrix.getTranspose();

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

	deviceContext.VSSetConstantBuffers( 0, 1, m_constantInputBuffer.GetAddressOf() );
}
Esempio n. 27
0
//--------------------------------------------------------------------------------------------------------------------
void RDX11RenderHelper::DrawLine()
{
	UINT dataBytes = m_LineVertices.GetSize() * sizeof( CVertexPC );
	if( m_LineBufferBytes < dataBytes )
	{
		SAFE_RELEASE( m_pLineBuffer );
		m_LineBufferBytes = dataBytes;

		D3D11_BUFFER_DESC BufferDesc;
		BufferDesc.ByteWidth = m_LineBufferBytes;
		BufferDesc.Usage = D3D11_USAGE_DYNAMIC;
		BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		BufferDesc.MiscFlags = 0;

		GLOBAL::D3DDevice()->CreateBuffer( &BufferDesc, NULL, &m_pLineBuffer );
		DXUT_SetDebugName( m_pLineBuffer, "LineBuffer" );
	}

	//////////////////////////////////////////////////////////////////////////
	// refresh vertex buffer
	ID3D11DeviceContext* pContext = GLOBAL::D3DContext();
	D3D11_MAPPED_SUBRESOURCE MappedResource;
	if ( S_OK == pContext->Map( m_pLineBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) 
	{ 
		CopyMemory( MappedResource.pData, (void*)m_LineVertices.GetData(), dataBytes );
		pContext->Unmap(m_pLineBuffer, 0);
	}

	//////////////////////////////////////////////////////////////////////////
	// Draw
	UINT Stride = sizeof( CVertexPC );
	UINT Offset = 0;

	GLOBAL::RenderStateMgr()->SetTopology(D3D_PRIMITIVE_TOPOLOGY_LINELIST);
	GLOBAL::RenderStateMgr()->SetVertexInput(FVF_3FP_1DC);
	pContext->IASetVertexBuffers( 0, 1, &m_pLineBuffer, &Stride, &Offset );
	pContext->Draw( m_LineVertices.GetSize(), 0 );

	m_LineVertices.Reset();
}
Esempio n. 28
0
void CGUIShaderDX::DrawQuad(Vertex& v1, Vertex& v2, Vertex& v3, Vertex& v4)
{
  if (!m_bCreated)
    return;

  ApplyChanges();

  ID3D11DeviceContext* pContext = g_Windowing.Get3D11Context();

  // update vertex buffer
  D3D11_MAPPED_SUBRESOURCE resource;
  if (SUCCEEDED(pContext->Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource)))
  {
    // we are using strip topology
    Vertex vertices[4] = { v2, v3, v1, v4 };
    memcpy(resource.pData, &vertices, sizeof(Vertex) * 4);
    pContext->Unmap(m_pVertexBuffer, 0);
    // Draw primitives
    pContext->Draw(4, 0);
  }
}
Esempio n. 29
0
//-----------------------------------------------------------------------------
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()
Esempio n. 30
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;
}