void CFullscreenTriangleDrawer::DrawDX11( ID3D11ShaderResourceView* pTextureSRV )
    {
        ID3D11Device* pDevice = static_cast<ID3D11Device*>( gD3DDevice );
        ID3D11DeviceContext* pContext = NULL;
        pDevice->GetImmediateContext( &pContext );

        CDX11StateGuard stateGuard;

        pContext->IASetInputLayout( NULL );
        pContext->IASetIndexBuffer( NULL, DXGI_FORMAT_UNKNOWN, 0 );
        pContext->IASetVertexBuffers( 0, 0, NULL, NULL, NULL );
        pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

        pContext->VSSetShader( m_pVertexShader11, NULL, 0 );
        pContext->PSSetShader( m_pPixelShader11, NULL, 0 );
        ID3D11SamplerState* pNullSampler[] = { NULL };
        pContext->PSSetSamplers( 0, 1, pNullSampler );

        pContext->PSSetShaderResources( 0, 1, &pTextureSRV );

        pContext->OMSetBlendState( m_pBlendState11, NULL, 0xFFFFFFFF );

        // Draw
        pContext->Draw( 3, 0 );
    }
Beispiel #2
0
	void Render::Draw()
	{
		UINT stride = sizeof(GENERIC::Vertex);
		UINT offset = 0;

		ID3D11DeviceContext* context = RenderDevice::Get()->GetContext();

		context->IASetInputLayout(_inputLayout);
		context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

		context->IASetVertexBuffers(0, 1, &pVB, &stride, &offset);
		context->IASetIndexBuffer(pIB, DXGI_FORMAT_R32_UINT, 0);

		D3DX11_TECHNIQUE_DESC	techDesc;
		_tech->GetDesc(&techDesc);

		XMMATRIX world	= pOwner->GetComponent<Transform>()->GetWorldMatrix();
		XMMATRIX vp		= General::Get()->GetMainCamera()->GetViewProjectionMatrix();
		
		Effect::BasicEffect::Get()->SetWorldMatrix(reinterpret_cast<float*>(&world));
		Effect::BasicEffect::Get()->SetViewProjectionMatrix(reinterpret_cast<float*>(&vp));

		for (UINT i = 0; i < techDesc.Passes; ++i)
		{
			_tech->GetPassByIndex(i)->Apply(0, context);
			context->DrawIndexed(_meshData->GetNumIndices(), 0, 0);
		}
	}
Beispiel #3
0
bool SkyBox::Render(std::shared_ptr<D3DRenderer> d3d, DirectX::CXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection, std::shared_ptr<Camera> camera, std::shared_ptr<Light> light)
{
	ID3D11DeviceContext *context = d3d->GetDeviceContext();
	DirectX::XMMATRIX sphereWorld = DirectX::XMMatrixIdentity(), scale = DirectX::XMMatrixScaling(0.3f, 0.3f, 0.3f), translation;

	translation = DirectX::XMMatrixTranslationFromVector(camera->GetPosition());
	sphereWorld = scale * translation;

	if (!SetShaderParameters(context, sphereWorld, view, projection, texture->GetTexture()))
		return false;

	UINT strides = sizeof(DirectX::VertexPositionNormalTexture), offset = 0;

	context->IASetInputLayout(m_layout);
	context->IASetIndexBuffer(sphereIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
	context->IASetVertexBuffers(0, 1, &sphereVertBuffer, &strides, &offset);
	context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	
	context->PSSetShader(pixelShader, NULL, 0);
	context->VSSetShader(vertexShader, NULL, 0);
	context->RSSetState(d3d->GetRasterState(1));

	d3d->SetDepthLessEqual();

	context->DrawIndexed(NumSphereFaces*3, 0, 0);

	d3d->End2D();

	context->RSSetState(d3d->GetRasterState(0));

	return true;
}
//---------------------------------------------------------------------------
void ShadowMapGen::DrawRenderable(const RenderableNode& r)
{
    if (!r.GetFlag( RenderableNode::kShadowCaster ) )
        return;

    ID3D11DeviceContext* dc = m_rc->Context();

    ConstantBufferShadowMapGenPerDraw constBuffer;
    Matrix::Transpose(r.WorldXform, constBuffer.world );    
    UpdateConstantBuffer(dc,m_pConstantBufferPerDraw,&constBuffer,sizeof(constBuffer));
    
    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_R32_UINT, 0);

    dc->DrawIndexed(indexCount, startIndex, startVertex);
}
Beispiel #5
0
void entity::draw(ID3D11DeviceContext& device, const camera& camera, shadow_map& shadow_map) const
{
	this->update_world_matrix();

	this->shader.vertex.set_data("world", this->world_matrix);
	this->shader.vertex.set_data("view", camera.view_mat());
	this->shader.vertex.set_data("projection", camera.projection);
	this->shader.vertex.set_data("shadowView", shadow_map.light_view);
	this->shader.vertex.set_data("shadowProjection", shadow_map.light_projection);
	this->shader.pixel.set_sampler_state("state", this->shader_texture.state);
	this->shader.pixel.set_shader_resource_view("res", this->shader_texture.resource_view);
	this->shader.pixel.set_shader_resource_view("shadowMap", shadow_map.shadow.resource_view);
	this->shader.pixel.set_sampler_state("shadowSampler", shadow_map.shadow.sampler_state);

	this->shader.vertex.activate(true);
	this->shader.pixel.activate(true);
	UINT stride = sizeof(Vertex);
	UINT offset = 0;
	device.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	device.IASetVertexBuffers(0, 1, &this->object_mesh.vertices.buffer, &stride, &offset);
	device.IASetIndexBuffer(this->object_mesh.indices.buffer, DXGI_FORMAT_R32_UINT, 0);
	device.DrawIndexed(
		this->object_mesh.indices.len,
		0,   
		0);   

}
//---------------------------------------------------------------------------
void FontRenderer::FontDrawingBegin(  RenderContext* rc )
{
    assert( m_vertexBuffer != NULL );
    assert( m_indexBuffer != NULL );

    m_currentRC = rc;

    m_fontDrawOps.clear();

    ID3D11DeviceContext* dc = m_currentRC->Context();

    UINT viewportCount = 1;
    D3D11_VIEWPORT vp;
    dc->RSGetViewports(&viewportCount, &vp);

    UINT stride = sizeof(FontTextVertex);
    UINT offset = 0;
    dc->IASetInputLayout(m_vertexLayout);
    dc->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
    dc->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
    dc->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    dc->VSSetShader( m_vertexShader, 0, 0 );
    dc->PSSetShader( m_pixelShader, 0, 0 );
    dc->PSSetSamplers( 0, 1, &m_samplerState );

    dc->RSSetState(m_rasterState);

    float blendFactor[4] = {1.0f};
    dc->OMSetBlendState(m_blendState, blendFactor, 0xffffffff);

    m_activeFont = NULL;    // needs to be set!
}
void ComplexTree::draw(ID3D11Device* device, const GameTime& gameTime)
{
	ID3D11DeviceContext* deviceContext;
	device->GetImmediateContext(&deviceContext);

	ID3D11Buffer* buffers[2] = { trunkMesh.GetVB11(0, 0), instanceBuffer };
	unsigned strides[2] = { trunkMesh.GetVertexStride(0,0), sizeof(Vector3) };
	unsigned offsets[2] = {0};
	deviceContext->IASetInputLayout(inputLayout);
	deviceContext->IASetVertexBuffers(0, 2, buffers, strides, offsets);
	deviceContext->IASetIndexBuffer(trunkMesh.GetIB11(0), trunkMesh.GetIBFormat11(0), 0);

	Camera& camera = vegetationRendering.getCamera();
	const Light& light = vegetationRendering.getLight();

	D3D11_VIEWPORT viewport;
	unsigned numViewports = 1;
	deviceContext->RSGetViewports(&numViewports, &viewport);

	evGSCulling->SetBool(vegetationRendering.isGSCullingEnabled());
	evShowSavedCulling->SetBool(vegetationRendering.showSaved());
	evSavedViewProjection->SetMatrix(vegetationRendering.getSavedViewMatrix() * vegetationRendering.getSavedProjectionMatrix());
	evCameraPosition->SetFloatVector(camera.getPosition());
	evLightVector->SetFloatVector(Vector3(light.Direction.x, light.Direction.y, light.Direction.z));
	evAmbientLight->SetFloatVector(Vector3(light.Ambient.r, light.Ambient.g, light.Ambient.b));
	evDiffuseLight->SetFloatVector(Vector3(light.Diffuse.r, light.Diffuse.g, light.Diffuse.b));
	evSpecularLight->SetFloatVector(Vector3(light.Specular.r, light.Specular.g, light.Specular.b));
	evShininess->SetFloat(TREE_SHININESS);

	evWorld->SetMatrix(world);
	evViewProjection->SetMatrix(camera.getView() * camera.getProjection(TREE_NEAR_PLANE, TREE_FAR_PLANE));

	for(unsigned i = 0; i < trunkMesh.GetNumSubsets(0); ++i)
	{
		SDKMESH_SUBSET* subset = trunkMesh.GetSubset(0, i);
		//D3D11_PRIMITIVE_TOPOLOGY primitiveType = trunkMesh.GetPrimitiveType11((SDKMESH_PRIMITIVE_TYPE)subset->PrimitiveType);
		deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST);
		SDKMESH_MATERIAL* material = trunkMesh.GetMaterial(subset->MaterialID);
		if(material)
			evTrunkTexture->SetResource(material->pDiffuseRV11);
		pass->Apply(0, deviceContext);
		deviceContext->DrawIndexedInstanced((unsigned)subset->IndexCount, drawInstanceCount,
			(unsigned)subset->IndexStart, (int)subset->VertexStart,0);
		//deviceContext->DrawIndexed((unsigned)subset->IndexCount, (unsigned)subset->IndexStart, (int)subset->VertexStart);
	}

	/*deviceContext->IASetInputLayout(inputLayoutLOD1);
	unsigned stride = sizeof(float) * 3;
	unsigned offset = 0;
	deviceContext->IASetVertexBuffers(0, 1, &instanceBuffer, &stride, &offset);
	deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);

	evWorld->SetMatrix(Matrix::createScale(Vector3(9)));

	passLOD1->Apply(0, deviceContext);
	deviceContext->Draw(INSTANCE_COUNT, 0);*/

	deviceContext->Release();
}
Beispiel #8
0
void Mesh::DrawIndexed()
{
	ID3D11DeviceContext * context = GetContext();
	unsigned int offset = 0;
	context->IASetVertexBuffers(0,1,&vertexBuffer,&stride,&offset);
	context->IASetIndexBuffer(indexBuffer,DXGI_FORMAT_R32_UINT,0);
	context->IASetPrimitiveTopology(topology);

	context->DrawIndexed(numberOfIndecies,0,0);
}
Beispiel #9
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 FBXObject::SetupDrawVertexBuffer()
{
	ID3D11DeviceContext* pImmediateContext = DX11App::getInstance()->direct3d.pImmediateContext;

	UINT stride = sizeof( cFBXBuffer::SimpleSkinnedVertex );
    UINT offset = 0;
	pImmediateContext->IASetVertexBuffers( 0, 1, &(this->pMeshVertexBuffer.second), &stride, &offset );
	pImmediateContext->IASetIndexBuffer( this->pMeshIndexBuffer.second, DXGI_FORMAT_R16_UINT, 0 );
    pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

}
void DXIndexBuffer::activate(){
  ID3D11DeviceContext* ctx = static_cast< DXRenderer* >(Engine::instance()->getRenderer())->getContext();
  DXGI_FORMAT fmt;
  if (mType == IB_UCHAR)
    fmt = DXGI_FORMAT_R8_UINT;
  else if (mType == IB_USHORT)
    fmt = DXGI_FORMAT_R16_UINT;
  else if (mType == IB_UINT)
    fmt = DXGI_FORMAT_R32_UINT;
  ctx->IASetIndexBuffer(mIb, fmt, 0);
}
            ~CDX11StateGuard()
            {
                ID3D11Device* pDevice = static_cast<ID3D11Device*>( gD3DDevice );
                ID3D11DeviceContext* pContext = NULL;
                pDevice->GetImmediateContext( &pContext );

                // Apply saved state
                pContext->OMSetBlendState( m_pBlendState, m_BlendFactor, m_SampleMask );
                pContext->RSSetState( m_pRasterizerState );
                pContext->IASetPrimitiveTopology( m_PrimitiveTopology );
                pContext->IASetIndexBuffer( m_pIndexBuffer, m_IndexBufferFormat, m_IndexBufferOffset );
                pContext->IASetInputLayout( m_pInputLayout );
                pContext->IASetVertexBuffers( 0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT, m_pVertexBuffers, m_pVertexBufferStrides, m_pVertexBufferOffsets );
                pContext->VSSetShader( m_pVertexShader, m_ppVertexShaderClassInstances, m_VertexShaderClassInstancesCount );
                pContext->PSSetShader( m_pPixelShader, m_ppPixelShaderClassInstances, m_PixelShaderClassInstancesCount );
                pContext->PSSetSamplers( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, m_ppPixelShaderSamplers );
                pContext->PSSetShaderResources( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, m_ppPixelShaderResources );

                // Release references
                SAFE_RELEASE( m_pBlendState );
                SAFE_RELEASE( m_pRasterizerState );
                SAFE_RELEASE( m_pIndexBuffer );
                SAFE_RELEASE( m_pInputLayout );

                for ( UINT i = 0; i < D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT; ++i )
                {
                    SAFE_RELEASE( m_pVertexBuffers[i] );
                }

                SAFE_RELEASE( m_pVertexShader );

                for ( UINT i = 0; i < m_VertexShaderClassInstancesCount; ++i )
                {
                    SAFE_RELEASE( m_ppVertexShaderClassInstances[i] );
                }

                SAFE_RELEASE( m_pPixelShader );

                for ( UINT i = 0; i < m_PixelShaderClassInstancesCount; ++i )
                {
                    SAFE_RELEASE( m_ppPixelShaderClassInstances[i] );
                }

                for ( UINT i = 0; i < D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT; ++i )
                {
                    SAFE_RELEASE( m_ppPixelShaderSamplers[i] );
                }

                for ( UINT i = 0; i < D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT; ++i )
                {
                    SAFE_RELEASE( m_ppPixelShaderResources[i] );
                }
            }
Beispiel #13
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);
}
Beispiel #14
0
		void DiffuseModel::renderBuffers()
		{
			unsigned int stride;
			unsigned int offset;

			stride = sizeof(VertexType);
			offset = 0;

			ID3D11DeviceContext * deviceContext = GraphicsDX::GetDeviceContext();
			deviceContext->IASetVertexBuffers(0, 1, &_vertexBuffer, &stride, &offset);
			deviceContext->IASetIndexBuffer(_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
			deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
		}
//---------------------------------------------------------------------------
void TexturedShader::DrawRenderable(const RenderableNode& r)
{

    // update per draw cb.
    ID3D11DeviceContext*  dc = m_rc->Context();
    ID3D11ShaderResourceView* textures[] = {NULL, NULL, NULL};
           
    ConstantBufferPerDraw constBuff;

    Matrix::Transpose(r.WorldXform, constBuff.cb_world );
    constBuff.cb_hasDiffuseMap = 0;
    constBuff.cb_hasNormalMap = 0;
    constBuff.cb_hasSpecularMap = 0;
    constBuff.cb_lighting =  r.lighting;

    Matrix w = r.WorldXform;        
    w.M41 = w.M42 = w.M43 = 0; w.M44 = 1;
    Matrix::Invert(w,constBuff.cb_worldInvTrans);
    Matrix::Transpose(r.TextureXForm, constBuff.cb_textureTrans);
    constBuff.cb_matDiffuse     = r.diffuse;
    constBuff.cb_matEmissive    = r.emissive;
    constBuff.cb_matSpecular    = float4(r.specular.x,r.specular.y, r.specular.z, r.specPower);

    if(r.textures[TextureType::DIFFUSE])
    {
        constBuff.cb_hasDiffuseMap = 1;
        textures[0] = r.textures[TextureType::DIFFUSE]->GetView();
    }

    if(r.textures[TextureType::NORMAL])
    {
        constBuff.cb_hasNormalMap = 1;
        textures[1] = r.textures[TextureType::NORMAL]->GetView();
    }
        
    UpdateConstantBuffer(dc,m_pConstantBufferPerDraw,&constBuff, sizeof(constBuff));    
    dc->PSSetShaderResources( 0, ARRAY_SIZE(textures), textures );
            
    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_R32_UINT, 0);
    dc->DrawIndexed(indexCount, startIndex, startVertex);
}
Beispiel #16
0
void entity::draw_with_activated_shader(ID3D11DeviceContext& device, vertex_shader& activated_vertex_shader) const
{ 
	this->update_world_matrix();

	activated_vertex_shader.set_data("world", this->world_matrix);
	activated_vertex_shader.copy_all_buffers();

	UINT stride = sizeof(Vertex);
	UINT offset = 0;
	device.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	device.IASetVertexBuffers(0, 1, &this->object_mesh.vertices.buffer, &stride, &offset);
	device.IASetIndexBuffer(this->object_mesh.indices.buffer, DXGI_FORMAT_R32_UINT, 0);
	device.DrawIndexed(
		this->object_mesh.indices.len,
		0,
		0);
}
/*
	Renders entity
*/
void CEntity::Render(unsigned int &prevMeshID) const 
{
	if (mRenderEntity)
	{
		CRenderManager* rm = CRenderManager::GetInstance();
		ID3D11DeviceContext* deviceContext = rm->GetDeviceContext();
		geom::CMesh* mesh = mTemplate->mMesh;

		if (mesh != NULL)
		{
			if (mesh->GetUID() != prevMeshID)
			{		
				/* Sets the buffers */
				ID3D11Buffer* vertexBuffer = mesh->GetVertexBuffer();
				ID3D11Buffer* indexBuffer = mesh->GetIndexBuffer();

				UINT stride = mesh->GetVertexSize();
				UINT offset = 0;

				deviceContext->IASetVertexBuffers( 0, 1, &vertexBuffer, &stride, &offset );
				deviceContext->IASetIndexBuffer( indexBuffer, DXGI_FORMAT_R16_UINT, 0 );

				deviceContext->IASetPrimitiveTopology( mesh->GetTopology() );

				/* Sets texture */
				ID3D11ShaderResourceView* texture = mesh->GetTexture();
				if (texture != NULL)
				{
					ID3D11SamplerState* sample = mesh->GetSample();
					int startSlot = mesh->GetStartSlot();

					deviceContext->PSSetShaderResources( startSlot, 1, &texture );
					deviceContext->PSSetSamplers( startSlot, 1, &sample );

					deviceContext->RSSetState( mTemplate->mRasterState );
				}
			}

			deviceContext->DrawIndexed( mesh->GetNumberOfIndices(), 0, 0 );

			prevMeshID = mesh->GetUID();
		}
	}
}
	void CubeDemo::draw(const GameTimer & timer)
	{
		ID3D11DeviceContext * deviceContext = mGame->deviceContext();
		deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
		deviceContext->IASetInputLayout(mInputLayout);

		UINT stride = sizeof(BasicEffectVertex);
		UINT offset = 0;
		deviceContext->IASetVertexBuffers(0, 1, &mVertexBuffer, &stride, &offset);
		deviceContext->IASetIndexBuffer( mIndexBuffer, DXGI_FORMAT_R32_UINT, 0);

		XMMATRIX worldMatrix = XMLoadFloat4x4(&mWorldMatrix);
		XMMATRIX wvp = worldMatrix * mCamera->viewMatrix() * mCamera->projectionMatrix();
		mWvpVariable->SetMatrix(reinterpret_cast<float*>(&wvp));

		mPass->Apply(0, deviceContext);
		deviceContext->DrawIndexed(36,0, 0);

	}
//-----------------------------------------------------------------------------
void CPUTMeshDX11::Draw(CPUTRenderParameters &renderParams, CPUTModel *pModel, ID3D11InputLayout *pInputLayout )
{
	mDrawCallCount++;
    // Skip empty meshes.
    if( !mIndexCount ) { return; }

// TODO: Modify CPUTPerfTaskMarker so that calls compile out, instead of explicitly wrapping every call with ifdef CPUT_GPA_INSTRUMENTATION
#ifdef CPUT_GPA_INSTRUMENTATION
    CPUTPerfTaskMarker marker = CPUTPerfTaskMarker(D3DCOLOR(0xff0000), _L("CPUT Draw Mesh"));
#endif
    ID3D11DeviceContext *pContext = ((CPUTRenderParametersDX*)&renderParams)->mpContext;

    pContext->IASetPrimitiveTopology( mD3DMeshTopology );
    pContext->IASetVertexBuffers(0, 1, &mpVertexBuffer, &mVertexStride, &mVertexBufferOffset);
    pContext->IASetIndexBuffer(mpIndexBuffer, mIndexBufferFormat, 0);

    pContext->IASetInputLayout( pInputLayout );

    pContext->DrawIndexed( mIndexCount, 0, 0 );
}
Beispiel #20
0
	//----------------------------------------------------------------------------------------------------
	bool EEPoints2D::Render()
	{
		if (!EEObject::Render())
			return false;

		MapObjectBuffer();

		ID3D11DeviceContext *deviceContext = EECore::s_EECore->GetDeviceContext();
		deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
		deviceContext->IASetInputLayout(s_pointsIL);
		UINT stride = sizeof(EEPoints2DVertex);
		UINT offset = 0;
		deviceContext->IASetVertexBuffers(0, 1, &m_pointsVB, &stride, &offset);
		deviceContext->IASetIndexBuffer(NULL, DXGI_FORMAT_R32_UINT, 0);
		deviceContext->VSSetShader(s_pointsVS, NULL, 0);
		deviceContext->PSSetShader(s_pointsPS, NULL, 0);
		deviceContext->Draw(m_points.size(), 0);

		return true;
	}
Beispiel #21
0
	//----------------------------------------------------------------------------------------------------
	bool EECylinder::Render()
	{
		if (!EEObject::Render())
			return false;

		MapObjectBuffer();

		ID3D11DeviceContext *deviceConstext = EECore::s_EECore->GetDeviceContext();
		deviceConstext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
		deviceConstext->IASetInputLayout(s_objectIL);
		UINT stride = sizeof(EECylinderVertex);
		UINT offset = 0;
		deviceConstext->IASetVertexBuffers(0, 1, &m_objectVB, &stride, &offset);
		deviceConstext->IASetIndexBuffer(m_objectIB, DXGI_FORMAT_R32_UINT, 0);
		deviceConstext->VSSetShader(s_objectVS, NULL, 0);
		ID3D11ShaderResourceView *texture = m_tex.GetTexture();
		deviceConstext->PSSetShaderResources(0, 1, &texture);
		deviceConstext->PSSetShader(s_objectPS, NULL, 0);
		deviceConstext->DrawIndexed(m_indexCount, 0, 0);

		return true;
	}
Beispiel #22
0
	//----------------------------------------------------------------------------------------------------
	bool EECurve2D::Render()
	{
		if (!EEObject::Render())
			return false;

		MapObjectBuffer();

		ID3D11DeviceContext *deviceContext = EECore::s_EECore->GetDeviceContext();
		deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
		deviceContext->IASetInputLayout(s_curveIL);
		UINT stride = sizeof(EECurve2DVertex);
		UINT offset = 0;
		deviceContext->IASetVertexBuffers(0, 1, &m_curveVB, &stride, &offset);
		deviceContext->IASetIndexBuffer(NULL, DXGI_FORMAT_R32_UINT, 0);
		deviceContext->VSSetShader(s_curveVS, NULL, 0);
		ID3D11ShaderResourceView *texture = m_tex.GetTexture();
		deviceContext->PSSetShaderResources(0, 1, &texture);
		deviceContext->PSSetShader(s_curvePS, NULL, 0);
		deviceContext->Draw(m_curve.size() << 1, 0);

		return true;
	}
Beispiel #23
0
//-----------------------------------------------------------------------------
void CPUTMeshDX11::Draw()
{
    // Skip empty meshes.
    if( mIndexCount == 0 && mVertexCount == 0)
     return; 


    ID3D11DeviceContext *pContext = CPUT_DX11::GetContext();

    pContext->IASetPrimitiveTopology( mD3DMeshTopology );
    pContext->IASetVertexBuffers(0, 1, &mpVertexBuffer, &mVertexStride, &mVertexBufferOffset);

    if (mIndexCount) 
    {
        pContext->IASetIndexBuffer(mpIndexBuffer, mIndexBufferFormat, 0);
        pContext->DrawIndexed( mIndexCount, 0, 0 );
    }
    else 
    {
        pContext->Draw( mVertexCount, 0 );
    }
}
//-----------------------------------------------------------------------------
void CPUTMeshDX11::Draw(CPUTRenderParameters &renderParams, ID3D11InputLayout *pInputLayout )
{
    // Skip empty meshes.
    //if( !mIndexCount ) { return; }


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

    pContext->IASetPrimitiveTopology( mD3DMeshTopology );
    pContext->IASetVertexBuffers(0, 1, &mpVertexBuffer, &mVertexStride, &mVertexBufferOffset);

    if (mIndexCount) {
        pContext->IASetIndexBuffer(mpIndexBuffer, mIndexBufferFormat, 0);
    }

    pContext->IASetInputLayout( pInputLayout );

    if (mIndexCount) {
        pContext->DrawIndexed( mIndexCount, 0, 0 );
    } else {
        pContext->Draw( mVertexCount, 0 );
    }
}
	void GfxEntityHeightMap::render(const XMMATRIX& _world, const XMMATRIX& _view, const XMMATRIX& _projection, const XMVECTOR& _color,
		const Texture* const _texture, bool _wireframe)
	{
		UNREFERENCED_PARAMETER(_color);
		UNREFERENCED_PARAMETER(_texture);

		// Set vertex buffer stride and offset.
		unsigned int stride = sizeof(VertexPositionNormalColor);
		unsigned int offset = 0;

		if (_wireframe)
			GRAPHICS->getDirectXWrapper()->turnOnWireframeMode();


		ID3D11DeviceContext* context = GRAPHICS->getDirectXWrapper()->getDeviceContext();
		m_effect->SetWorld(_world);
		m_effect->SetView(_view);
		m_effect->SetProjection(_projection);
		m_effect->DisableSpecular();
		m_effect->SetAmbientLightColor(XMVectorSet(1, 1, 1, 1));
		m_effect->Apply(context);
		
		context->IASetInputLayout(m_inputLayout);

		// Set the vertex buffer to active in the input assembler so it can be rendered.
		context->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
		
		// Set the index buffer to active in the input assembler so it can be rendered.
		context->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
		
		// Set the type of primitive that should be rendered from this vertex buffer, in this case triangles.
		context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
		context->DrawIndexed(m_indicesCount, 0, 0);

		if (_wireframe)
			GRAPHICS->getDirectXWrapper()->turnOnFillMode();
	}
void Terrain::draw(ID3D11Device* device, const GameTime& gameTime)
{
    ID3D11DeviceContext* deviceContext;
    device->GetImmediateContext(&deviceContext);

    deviceContext->IASetInputLayout(inputLayout);
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);

    unsigned strides[2] = { sizeof(TerrainVertex), sizeof(TerrainInstance) };
    unsigned offsets[2] = { 0, 0 };
    ID3D11Buffer* buffers[2] = { vertexBuffer, instanceBuffer };
    deviceContext->IASetVertexBuffers(0, 2, buffers, strides, offsets);
    deviceContext->IASetIndexBuffer(indexBuffer, DXGI_FORMAT_R32_UINT, 0);

    Camera& camera = vegetationRendering.getCamera();
    evWorld->SetMatrix(world);
    evViewProjection->SetMatrix(camera.getView() * camera.getProjection());

    pass->Apply(0, deviceContext);
    deviceContext->DrawIndexedInstanced(4, INSTANCE_COUNT, 0, 0, 0);
    //deviceContext->DrawInstanced(4, INSTANCE_COUNT, 0, 0);

    deviceContext->Release();
}
Beispiel #27
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);
}
Beispiel #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;
}
Beispiel #29
0
bool D11State::init() {
	HRESULT hr;

	ID3D11Texture2D* pBackBuffer = NULL;
	hr = pSwapChain->GetBuffer(0, __uuidof(*pBackBuffer), (LPVOID*)&pBackBuffer);
	if (FAILED(hr)) {
		ods("D3D11: pSwapChain->GetBuffer failure!");
		return false;
	}

	hr = pDevice->CreateDeferredContext(0, &pDeviceContext);
	// Depending on the device settings a deferred context may not be createable
	// for example if it is a SINGLETHREADED device.
	// (See http://msdn.microsoft.com/en-us/library/windows/desktop/ff476505%28v=vs.85%29.aspx)
	// We handle the expected failure and failure fallback in the same way -
	// by trying to use an immediate context.
	if (FAILED(hr) || !pDeviceContext) {
		ods("D3D11: Failed to create DeferredContext (0x%x). Getting ImmediateContext", hr);
		pDevice->GetImmediateContext(&pDeviceContext);
		D11CreateStateBlock(pDeviceContext, &pOrigStateBlock);
		D11CreateStateBlock(pDeviceContext, &pMyStateBlock);

		pOrigStateBlock->Capture();
		bDeferredContext = false;
	} else {
		bDeferredContext = true;
	}

	D3D11_TEXTURE2D_DESC backBufferSurfaceDesc;
	pBackBuffer->GetDesc(&backBufferSurfaceDesc);

	ZeroMemory(&vp, sizeof(vp));
	vp.Width = static_cast<float>(backBufferSurfaceDesc.Width);
	vp.Height = static_cast<float>(backBufferSurfaceDesc.Height);
	vp.MinDepth = 0;
	vp.MaxDepth = 1;
	vp.TopLeftX = 0;
	vp.TopLeftY = 0;
	pDeviceContext->RSSetViewports(1, &vp);

	hr = pDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRTV);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateRenderTargetView failed!");
		return false;
	}

	pDeviceContext->OMSetRenderTargets(1, &pRTV, NULL);

	// Settings for an "over" operation.
	// https://en.wikipedia.org/w/index.php?title=Alpha_compositing&oldid=580659153#Description
	D3D11_BLEND_DESC blend;
	ZeroMemory(&blend, sizeof(blend));
	blend.RenderTarget[0].BlendEnable = TRUE;
	blend.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
	blend.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blend.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blend.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	blend.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
	blend.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blend.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

	pDevice->CreateBlendState(&blend, &pBlendState);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateBlendState failed!");
		return false;
	}

	pDeviceContext->OMSetBlendState(pBlendState, NULL, 0xffffffff);

	hr = pDevice->CreateVertexShader(g_vertex_shader, sizeof(g_vertex_shader), NULL, &pVertexShader);
	if (FAILED(hr)) {
		ods("D3D11: Failed to create vertex shader.");
		return false;
	}

	hr = pDevice->CreatePixelShader(g_pixel_shader, sizeof(g_pixel_shader), NULL, &pPixelShader);
	if (FAILED(hr)) {
		ods("D3D11: Failed to create pixel shader.");
		return false;
	}

	pTexture = NULL;
	pSRView = NULL;

	// Define the input layout
	D3D11_INPUT_ELEMENT_DESC layout[] = {
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};

	hr = pDevice->CreateInputLayout(layout, ARRAY_NUM_ELEMENTS(layout), g_vertex_shader, sizeof(g_vertex_shader), &pVertexLayout);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateInputLayout failure!");
		return false;
	}

	pDeviceContext->IASetInputLayout(pVertexLayout);

	D3D11_BUFFER_DESC bd;
	ZeroMemory(&bd, sizeof(bd));
	bd.Usage = D3D11_USAGE_DYNAMIC;
	bd.ByteWidth = VERTEXBUFFER_SIZE;
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	bd.MiscFlags = 0;

	hr = pDevice->CreateBuffer(&bd, NULL, &pVertexBuffer);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateBuffer failure!");
		return false;
	}

	DWORD indices[] = {
		0,1,3,
		1,2,3,
	};

	ZeroMemory(&bd, sizeof(bd));
	bd.Usage = D3D11_USAGE_IMMUTABLE;
	bd.ByteWidth = sizeof(DWORD) * 6;
	bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	bd.CPUAccessFlags = 0;
	bd.MiscFlags = 0;
	D3D11_SUBRESOURCE_DATA InitData;
	ZeroMemory(&InitData, sizeof(InitData));
	InitData.pSysMem = indices;

	hr = pDevice->CreateBuffer(&bd, &InitData, &pIndexBuffer);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateBuffer failure!");
		return false;
	}

	// Set index buffer
	pDeviceContext->IASetIndexBuffer(pIndexBuffer, DXGI_FORMAT_R32_UINT, 0);

	// Set primitive topology
	pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	if (!bDeferredContext) {
		pMyStateBlock->Capture();
		pOrigStateBlock->Apply();
	}
	pBackBuffer->Release();

	return true;
}
		// 仮の実装
		BatchDrawOffset setBuffers(const size_t batchIndex)
		{
			BatchDrawOffset batchDrawOffset;

			//Log << L"{} - {} - {}"_fmt(batchIndex, m_batches[batchIndex].vertexPos, m_batches[batchIndex].indexPos);

			size_t vertexArrayOffset = 0;
			size_t indexArrayOffset = 0;

			for (size_t i = 0; i < batchIndex; ++i)
			{
				vertexArrayOffset += m_batches[i].vertexPos;
				indexArrayOffset += m_batches[i].indexPos;
			}

			{
				const Vertex2D* vertexData = m_vertices.data() + vertexArrayOffset;
				const uint32 vertexSize = m_batches[batchIndex].vertexPos;

				D3D11_MAP mapType = D3D11_MAP_WRITE_NO_OVERWRITE;

				if (VertexBufferSize < m_vertexBufferWritePos + vertexSize)
				{
					mapType = D3D11_MAP_WRITE_DISCARD;
					m_vertexBufferWritePos = 0;
				}

				D3D11_MAPPED_SUBRESOURCE vres;

				if (SUCCEEDED(m_context->Map(m_vertexBuffer.Get(), 0, mapType, 0, &vres)))
				{
					if (Vertex2D* const vtxbuf = static_cast<Vertex2D*>(vres.pData) + m_vertexBufferWritePos)
					{
						::memcpy(vtxbuf, vertexData, sizeof(Vertex2D) * vertexSize);

						m_context->Unmap(m_vertexBuffer.Get(), 0);
					}
				}

				batchDrawOffset.vertexStartLocation = m_vertexBufferWritePos;
				m_vertexBufferWritePos += vertexSize;
			}

			{
				const IndexType* indexData = m_indices.data() + indexArrayOffset;
				const uint32 indexSize = m_batches[batchIndex].indexPos;

				D3D11_MAP mapType = D3D11_MAP_WRITE_NO_OVERWRITE;

				if (IndexBufferSize < m_indexBufferWritePos + indexSize)
				{
					mapType = D3D11_MAP_WRITE_DISCARD;
					m_indexBufferWritePos = 0;
				}

				D3D11_MAPPED_SUBRESOURCE ires;

				if (FAILED(m_context->Map(m_indexBuffer.Get(), 0, mapType, 0, &ires)))
				{
					return{ 0, 0 };
				}

				if (IndexType* const idxbuf = static_cast<IndexType*>(ires.pData) + m_indexBufferWritePos)
				{
					::memcpy(idxbuf, indexData, sizeof(IndexType) * indexSize);

					m_context->Unmap(m_indexBuffer.Get(), 0);
				}

				batchDrawOffset.indexCount = indexSize;
				batchDrawOffset.indexStartLocation = m_indexBufferWritePos;
				m_indexBufferWritePos += indexSize;
			}

			ID3D11Buffer* const pBuf[3] = { m_vertexBuffer.Get(), nullptr, nullptr };

			const UINT stride[3] = { sizeof(Vertex2D), 0, 0 };

			const UINT offset[3] = { 0, 0, 0 };

			constexpr auto indexFormat = sizeof(IndexType) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;

			m_context->IASetVertexBuffers(0, 3, pBuf, stride, offset);

			m_context->IASetIndexBuffer(m_indexBuffer.Get(), indexFormat, 0);

			//Log << L"={} - {} - {}"_fmt(batchDrawOffset.indexCount, batchDrawOffset.indexStartLocation, batchDrawOffset.vertexStartLocation);

			return batchDrawOffset;
		}