Exemple #1
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 FBXObject::DrawObject()	
{
	ID3D11DeviceContext* pImmediateContext = DX11App::getInstance()->direct3d.pImmediateContext;

	pImmediateContext->DrawIndexed( this->AnimController.Mesh.second->mIndices.size(), 0, 0 );

}
//---------------------------------------------------------------------------
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);
}
Exemple #4
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;
}
Exemple #5
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);
		}
	}
Exemple #6
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);
}
Exemple #7
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);
}
Exemple #8
0
 void WaterRenderer::Render(const Camera* camera, Water* water, const Time& /*time*/, const RenderingSettings& /*settings*/) {
     ID3D11DeviceContext* context = lowLevelGraphics->GetDeviceContext();
     Effect* effect = effectResource->GetEffect();
     effect->SetParam("World", water->GetOwner()->GetTransform()->GetWorld());
     effect->SetParam("View", camera->GetView());
     effect->SetParam("Projection", camera->GetProjection());
     effect->SetParam("EyePosition", camera->GetPosition());
     effect->SetParam("Colormap", waterTextureResource->GetTexture());
     effect->Bind(context, "water", "forward", "pass0");
     quad->Bind(context, VertexChannelType::Geometry | VertexChannelType::Texture);
     context->DrawIndexed(quad->GetIndexCount(), 0, 0);
 }
Exemple #9
0
void D11State::draw() {
	clock_t t = clock();
	float elapsed = static_cast<float>(t - timeT) / CLOCKS_PER_SEC;
	++frameCount;
	if (elapsed > OVERLAY_FPS_INTERVAL) {
		OverlayMsg om;
		om.omh.uiMagic = OVERLAY_MAGIC_NUMBER;
		om.omh.uiType = OVERLAY_MSGTYPE_FPS;
		om.omh.iLength = sizeof(OverlayMsgFps);
		om.omf.fps = frameCount / elapsed;

		sendMessage(om);

		frameCount = 0;
		timeT = t;
	}

	checkMessage(static_cast<unsigned int>(vp.Width), static_cast<unsigned int>(vp.Height));

	if (a_ucTexture && pSRView && (uiLeft != uiRight)) {
		if (!bDeferredContext) {
			pOrigStateBlock->Capture();
			pMyStateBlock->Apply();
		}

		// Set vertex buffer
		UINT stride = sizeof(SimpleVertex);
		UINT offset = 0;
		pDeviceContext->IASetVertexBuffers(0, 1, &pVertexBuffer, &stride, &offset);

		pDeviceContext->VSSetShader(pVertexShader, NULL, 0);
		pDeviceContext->GSSetShader(NULL, NULL, 0);
		pDeviceContext->PSSetShaderResources(0, 1, &pSRView);
		pDeviceContext->PSSetShader(pPixelShader, NULL, 0);
		pDeviceContext->DrawIndexed(6, 0, 0);

		if (bDeferredContext) {
			ID3D11CommandList *pCommandList;
			pDeviceContext->FinishCommandList(TRUE, &pCommandList);
			ID3D11DeviceContext *ctx = NULL;
			pDevice->GetImmediateContext(&ctx);
			ctx->ExecuteCommandList(pCommandList, TRUE);
			ctx->Release();
			pCommandList->Release();
		} else {
			pDeviceContext->Flush();
			pMyStateBlock->Capture();
			pOrigStateBlock->Apply();
		}
	}
}
//---------------------------------------------------------------------------
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);
}
		void ProjectiveTextureShader::RenderShader(int indexCount)
		{
			ID3D11DeviceContext* deviceContext = GraphicsDX::GetDeviceContext();
			deviceContext->IASetInputLayout(m_layout);

			// Set the vertex and pixel shaders that will be used to render this triangle.
			deviceContext->VSSetShader(m_vertexShader, NULL, 0);
			deviceContext->PSSetShader(m_pixelShader, NULL, 0);

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

			// Render the triangle.
			deviceContext->DrawIndexed(indexCount, 0, 0);
		}
Exemple #12
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);
}
Exemple #13
0
const void ShaderClass::RenderShader(UINT indexCount, UINT indexStart)const
{
	ID3D11DeviceContext* c = SystemClass::GetInstance()->mGrapInst->GetContext();

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

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

	// Render mesh stored in active buffers
	c->DrawIndexed(indexCount, indexStart, 0);
}
/*
	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();
		}
	}
}
Exemple #15
0
    void GuiRenderer::RenderMenu(const Vector2f& position) {
        ID3D11DeviceContext* context = GraphicsManager::Get()->GetImmidiateContext();
        Effect* effect = effectResource->GetEffect();

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

        const MenuList* menu = GuiManager::Get()->GetMenu();
        const vector<IMenuEntry*>& entries = menu->GetEntries();

        Matrix transform = Matrix::CreateScale(0.25f, 0.075f, 1.0f) * Matrix::CreateTranslation(position.x / 1024.0f, position.y / 768.0f, 0.0f);

        effect->SetParam("World", transform);
        effect->SetParam("Texture", menuPanelTexture->GetTexture());
        effect->Bind("Gui", "Textured", "Pass0");

        context->DrawIndexed(quadVertexData->GetIndexCount(), 0, 0);

        // TODO
    }
	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);

	}
Exemple #17
0
		void FontShader::renderShader(int i_indexCount)
		{
			ID3D11DeviceContext* deviceContext = GraphicsDX::GetDeviceContext();

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

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

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

			// Render the triangles.
			deviceContext->DrawIndexed(i_indexCount, 0, 0);
		}
//-----------------------------------------------------------------------------
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 );
}
Exemple #19
0
    void PostProcessRenderer::RenderSSAO(const Camera* camera, Texture* positionBuffer, Texture* normalBuffer, Texture* finalBuffer) {
        ID3D11DeviceContext* context = GraphicsManager::Get()->GetImmidiateContext();
        const GraphicsManager::Configuration& config = GraphicsManager::Get()->GetConfiguration();
        _ASSERT(effectResource);
        Effect* effect = effectResource->GetEffect();

        graphics_extensions::UnbindAll();

        finalBuffer->BindRenderTarget();

        effect->SetParam("View", camera->GetView());
        effect->SetParam("PositionWBuffer", positionBuffer);
        effect->SetParam("NormalWBuffer", normalBuffer);
        effect->SetParam("RandomTexture", randomNormalsTexture->GetTexture());
        effect->SetParam("BufferDimensions", Vector2f(config.screenWidth, config.screenHeight));

        effect->Bind("PostProcessing", "SSAO", "Pass0");

        fullQuadData->Bind(VertexChannelType::Geometry);
        context->DrawIndexed(fullQuadData->GetIndexCount(), 0, 0);
    }   
Exemple #20
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;
	}
Exemple #21
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 );
    }
}
/** Draws a single pipeline-state */
void D3D11GraphicsEngineQueued::DrawPipelineState(const PipelineState* state)
{
	if (Engine::GAPI->GetRendererState()->RendererSettings.DisableDrawcalls)
		return;

	ID3D11DeviceContext* context = GetDeferredContextByThread();

	switch(state->BaseState.DrawCallType)
	{
	case PipelineState::DCT_DrawTriangleList:
		context->Draw(state->BaseState.NumVertices, 0);
		break;

	case PipelineState::DCT_DrawIndexed:
		context->DrawIndexed(state->BaseState.NumIndices, state->BaseState.IndexOffset, 0);
		break;

	case PipelineState::DCT_DrawIndexedInstanced:
		context->DrawIndexedInstanced(state->BaseState.NumIndices, state->BaseState.NumInstances, 0, 0, state->BaseState.InstanceOffset);
		break;
	}
}
//-----------------------------------------------------------------------------
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();
	}
Exemple #25
0
//---------------------------------------------------------------------------
void ShadowMapGen::DrawRenderable(const RenderableNode& r)
{
    if (!r.GetFlag( RenderableNode::kShadowCaster ) )
        return;

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

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

    dc->DrawIndexed(indexCount, startIndex, startVertex);
}
Exemple #26
0
    void GuiRenderer::RenderPanels() {
        Effect* effect = effectResource->GetEffect();

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

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

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

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

            context->DrawIndexed(quadVertexData->GetIndexCount(), 0, 0);
        }
    }
Exemple #27
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;
}
// Render function
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
{
    ID3D11DeviceContext* ctx = g_pd3dDeviceContext;

    // Create and grow vertex/index buffers if needed
    if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
    {
        if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
        g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
        D3D11_BUFFER_DESC desc;
        memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
        desc.Usage = D3D11_USAGE_DYNAMIC;
        desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
        desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
        desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
        desc.MiscFlags = 0;
        if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
            return;
    }
    if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
    {
        if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
        g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
        D3D11_BUFFER_DESC desc;
        memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
        desc.Usage = D3D11_USAGE_DYNAMIC;
        desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
        desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
        desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
        if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
            return;
    }

    // Copy and convert all vertices into a single contiguous buffer
    D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
    if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
        return;
    if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
        return;
    ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
    ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
        memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
        vtx_dst += cmd_list->VtxBuffer.Size;
        idx_dst += cmd_list->IdxBuffer.Size;
    }
    ctx->Unmap(g_pVB, 0);
    ctx->Unmap(g_pIB, 0);

    // Setup orthographic projection matrix into our constant buffer
    {
        D3D11_MAPPED_SUBRESOURCE mapped_resource;
        if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
            return;
        VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
        float L = 0.0f;
        float R = ImGui::GetIO().DisplaySize.x;
        float B = ImGui::GetIO().DisplaySize.y;
        float T = 0.0f;
        float mvp[4][4] =
        {
            { 2.0f/(R-L),   0.0f,           0.0f,       0.0f },
            { 0.0f,         2.0f/(T-B),     0.0f,       0.0f },
            { 0.0f,         0.0f,           0.5f,       0.0f },
            { (R+L)/(L-R),  (T+B)/(B-T),    0.5f,       1.0f },
        };
        memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
        ctx->Unmap(g_pVertexConstantBuffer, 0);
    }

    // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
    struct BACKUP_DX11_STATE
    {
        UINT                        ScissorRectsCount, ViewportsCount;
        D3D11_RECT                  ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
        D3D11_VIEWPORT              Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
        ID3D11RasterizerState*      RS;
        ID3D11BlendState*           BlendState;
        FLOAT                       BlendFactor[4];
        UINT                        SampleMask;
        UINT                        StencilRef;
        ID3D11DepthStencilState*    DepthStencilState;
        ID3D11ShaderResourceView*   PSShaderResource;
        ID3D11SamplerState*         PSSampler;
        ID3D11PixelShader*          PS;
        ID3D11VertexShader*         VS;
        UINT                        PSInstancesCount, VSInstancesCount;
        ID3D11ClassInstance*        PSInstances[256], *VSInstances[256];   // 256 is max according to PSSetShader documentation
        D3D11_PRIMITIVE_TOPOLOGY    PrimitiveTopology;
        ID3D11Buffer*               IndexBuffer, *VertexBuffer, *VSConstantBuffer;
        UINT                        IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
        DXGI_FORMAT                 IndexBufferFormat;
        ID3D11InputLayout*          InputLayout;
    };
    BACKUP_DX11_STATE old;
    old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
    ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
    ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
    ctx->RSGetState(&old.RS);
    ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
    ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
    ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
    ctx->PSGetSamplers(0, 1, &old.PSSampler);
    old.PSInstancesCount = old.VSInstancesCount = 256;
    ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
    ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
    ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
    ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
    ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
    ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
    ctx->IAGetInputLayout(&old.InputLayout);

    // Setup viewport
    D3D11_VIEWPORT vp;
    memset(&vp, 0, sizeof(D3D11_VIEWPORT));
    vp.Width = ImGui::GetIO().DisplaySize.x;
    vp.Height = ImGui::GetIO().DisplaySize.y;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = vp.TopLeftY = 0.0f;
    ctx->RSSetViewports(1, &vp);

    // Bind shader and vertex buffers
    unsigned int stride = sizeof(ImDrawVert);
    unsigned int offset = 0;
    ctx->IASetInputLayout(g_pInputLayout);
    ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
    ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
    ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
    ctx->VSSetShader(g_pVertexShader, NULL, 0);
    ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
    ctx->PSSetShader(g_pPixelShader, NULL, 0);
    ctx->PSSetSamplers(0, 1, &g_pFontSampler);

    // Setup render state
    const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
    ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
    ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
    ctx->RSSetState(g_pRasterizerState);

    // Render command lists
    int vtx_offset = 0;
    int idx_offset = 0;
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
        {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
                ctx->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
                ctx->RSSetScissorRects(1, &r);
                ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
            }
            idx_offset += pcmd->ElemCount;
        }
        vtx_offset += cmd_list->VtxBuffer.Size;
    }

    // Restore modified DX state
    ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
    ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
    ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
    ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
    ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
    ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
    ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
    ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
    for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
    ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
    ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
    for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
    ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
    ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
    ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
    ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
}
Exemple #29
0
// Render function
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
{
    // Avoid rendering when minimized
    if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
        return;

    ID3D11DeviceContext* ctx = g_pd3dDeviceContext;

    // Create and grow vertex/index buffers if needed
    if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
    {
        if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
        g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
        D3D11_BUFFER_DESC desc;
        memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
        desc.Usage = D3D11_USAGE_DYNAMIC;
        desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
        desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
        desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
        desc.MiscFlags = 0;
        if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
            return;
    }
    if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
    {
        if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
        g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
        D3D11_BUFFER_DESC desc;
        memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
        desc.Usage = D3D11_USAGE_DYNAMIC;
        desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
        desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
        desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
        if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
            return;
    }

    // Upload vertex/index data into a single contiguous GPU buffer
    D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
    if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
        return;
    if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
        return;
    ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
    ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
        memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
        vtx_dst += cmd_list->VtxBuffer.Size;
        idx_dst += cmd_list->IdxBuffer.Size;
    }
    ctx->Unmap(g_pVB, 0);
    ctx->Unmap(g_pIB, 0);

    // Setup orthographic projection matrix into our constant buffer
    // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
    {
        D3D11_MAPPED_SUBRESOURCE mapped_resource;
        if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
            return;
        VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
        float L = draw_data->DisplayPos.x;
        float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
        float T = draw_data->DisplayPos.y;
        float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
        float mvp[4][4] =
        {
            { 2.0f/(R-L),   0.0f,           0.0f,       0.0f },
            { 0.0f,         2.0f/(T-B),     0.0f,       0.0f },
            { 0.0f,         0.0f,           0.5f,       0.0f },
            { (R+L)/(L-R),  (T+B)/(B-T),    0.5f,       1.0f },
        };
        memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
        ctx->Unmap(g_pVertexConstantBuffer, 0);
    }

    // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
    struct BACKUP_DX11_STATE
    {
        UINT                        ScissorRectsCount, ViewportsCount;
        D3D11_RECT                  ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
        D3D11_VIEWPORT              Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
        ID3D11RasterizerState*      RS;
        ID3D11BlendState*           BlendState;
        FLOAT                       BlendFactor[4];
        UINT                        SampleMask;
        UINT                        StencilRef;
        ID3D11DepthStencilState*    DepthStencilState;
        ID3D11ShaderResourceView*   PSShaderResource;
        ID3D11SamplerState*         PSSampler;
        ID3D11PixelShader*          PS;
        ID3D11VertexShader*         VS;
        UINT                        PSInstancesCount, VSInstancesCount;
        ID3D11ClassInstance*        PSInstances[256], *VSInstances[256];   // 256 is max according to PSSetShader documentation
        D3D11_PRIMITIVE_TOPOLOGY    PrimitiveTopology;
        ID3D11Buffer*               IndexBuffer, *VertexBuffer, *VSConstantBuffer;
        UINT                        IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
        DXGI_FORMAT                 IndexBufferFormat;
        ID3D11InputLayout*          InputLayout;
    };
    BACKUP_DX11_STATE old;
    old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
    ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
    ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
    ctx->RSGetState(&old.RS);
    ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
    ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
    ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
    ctx->PSGetSamplers(0, 1, &old.PSSampler);
    old.PSInstancesCount = old.VSInstancesCount = 256;
    ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
    ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
    ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
    ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
    ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
    ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
    ctx->IAGetInputLayout(&old.InputLayout);

    // Setup desired DX state
    ImGui_ImplDX11_SetupRenderState(draw_data, ctx);

    // Render command lists
    // (Because we merged all buffers into a single one, we maintain our own offset into them)
    int global_idx_offset = 0;
    int global_vtx_offset = 0;
    ImVec2 clip_off = draw_data->DisplayPos;
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
        {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback != NULL)
            {
                // User callback, registered via ImDrawList::AddCallback()
                // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
                if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                    ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
                else
                    pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                // Apply scissor/clipping rectangle
                const D3D11_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) };
                ctx->RSSetScissorRects(1, &r);

                // Bind texture, Draw
                ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->TextureId;
                ctx->PSSetShaderResources(0, 1, &texture_srv);
                ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
            }
        }
        global_idx_offset += cmd_list->IdxBuffer.Size;
        global_vtx_offset += cmd_list->VtxBuffer.Size;
    }

    // Restore modified DX state
    ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
    ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
    ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
    ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
    ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
    ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
    ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
    ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
    for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
    ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
    ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
    for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
    ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
    ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
    ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
    ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
}
Exemple #30
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdLine, int cmdShow)
{
	DXTInputHandlerDefault inputHandler;
	DXTWindowEventHandlerDefault eventHandler;
	DXTWindow window(hInstance, &inputHandler, &eventHandler);

	DXTRenderParams params;
	params.Extent = { 800, 600 };
	params.UseVSync = true;
	params.Windowed = true;

	HRESULT result;
	result = window.Initialize(params, "DXT Example (DirectX 11)");

	if (SUCCEEDED(result))
	{
		ID3D11Device* device;
		ID3D11DeviceContext* context;
		IDXGISwapChain* swapChain;
		result = DXTInitDevice(params, &window, &swapChain, &device, &context);

		if (SUCCEEDED(result))
		{
			eventHandler.SetSwapChain(swapChain);

			FLOAT clearColor[] = { 0.5f, 0.5f, 1.0f, 1.0f };
			D3D11_INPUT_ELEMENT_DESC inputDesc[] =
			{
				{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
				{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, sizeof(float) * 3, D3D11_INPUT_PER_VERTEX_DATA, 0 },
				{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(float) * 5, D3D11_INPUT_PER_VERTEX_DATA, 0 },
			};
			UINT elementCount = 3;
			UINT stride = 8 * sizeof(FLOAT);
			UINT offset = 0;
			UINT indexCount = 0;
			FLOAT deltaTime = 0.016f;

			DXTSphericalCamera camera;
			DXTFirstPersonCameraController cameraController(&camera, &inputHandler);
			inputHandler.AddInputInterface(&cameraController);
			cameraController.Velocity = 40.0f;
			cameraController.RotationVelocity = 0.005f;
			camera.Position = DirectX::XMFLOAT3(20.0f, 20.0f, 20.0f);
			camera.LookAt(DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f));

			ID3D11RenderTargetView* renderTargetView;
			ID3D11Texture2D* depthBuffer;
			ID3D11DepthStencilView* depthBufferView;
			ID3D11VertexShader* vertexShader;
			ID3D11PixelShader* pixelShader;
			DXTBytecodeBlob vertexBytecode;
			ID3D11DepthStencilState* depthState;
			ID3D11RasterizerState* rasterizerState;
			ID3D11Buffer* vertexBuffer;
			ID3D11Buffer* indexBuffer;
			ID3D11InputLayout* inputLayout;
			ID3D11Buffer* transformBuffer;

			DXTCreateRenderTargetFromBackBuffer(swapChain, device, &renderTargetView);
			DXTCreateDepthStencilBuffer(device, params.Extent.Width, params.Extent.Height, DXGI_FORMAT_D24_UNORM_S8_UINT, &depthBuffer, &depthBufferView);
			DXTVertexShaderFromFile(device, "VertexShader.cso", &vertexShader, &vertexBytecode);
			DXTPixelShaderFromFile(device, "PixelShader.cso", &pixelShader);
			DXTCreateDepthStencilStateDepthTestEnabled(device, &depthState);
			DXTCreateRasterizerStateSolid(device, &rasterizerState);
			DXTLoadStaticMeshFromFile(device, "mesh.ase", DXTVertexAttributePosition | DXTVertexAttributeUV | DXTVertexAttributeNormal,
				DXTIndexTypeShort, &vertexBuffer, &indexBuffer, &indexCount);
			DXTCreateBuffer(device, sizeof(DirectX::XMFLOAT4X4) * 2, D3D11_BIND_CONSTANT_BUFFER, D3D11_CPU_ACCESS_WRITE, D3D11_USAGE_DYNAMIC, &transformBuffer);

			device->CreateInputLayout(inputDesc, elementCount, vertexBytecode.Bytecode, vertexBytecode.BytecodeLength, &inputLayout);
			vertexBytecode.Destroy();

			window.Present(false);

			while (!window.QuitMessageReceived())
			{
				window.MessagePump();

				if (inputHandler.IsKeyDown(VK_ESCAPE))
					break;

				cameraController.Update(deltaTime);

				XMFLOAT4X4 ViewProj;
				XMFLOAT4X4 World;
				camera.GetViewProjectionMatrix(&ViewProj, params.Extent);
				XMStoreFloat4x4(&World, XMMatrixIdentity());

				D3D11_MAPPED_SUBRESOURCE subres;
				context->Map(transformBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &subres);
				XMFLOAT4X4* ptr = (XMFLOAT4X4*)subres.pData;
				ptr[0] = World;
				ptr[1] = ViewProj;
				context->Unmap(transformBuffer, 0);

				D3D11_VIEWPORT viewport = { 0.0f, 0.0f, (FLOAT)params.Extent.Width, (FLOAT)params.Extent.Height, 0.0f, 1.0f };
				context->ClearRenderTargetView(renderTargetView, clearColor);
				context->ClearDepthStencilView(depthBufferView, D3D11_CLEAR_DEPTH, 1.0f, 0);
				context->OMSetDepthStencilState(depthState, 0);
				context->OMSetRenderTargets(1, &renderTargetView, depthBufferView);
				context->RSSetState(rasterizerState);
				context->RSSetViewports(1, &viewport);
				context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
				context->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
				context->IASetIndexBuffer(indexBuffer, DXGI_FORMAT_R16_UINT, 0);
				context->IASetInputLayout(inputLayout);
				context->VSSetShader(vertexShader, nullptr, 0);
				context->PSSetShader(pixelShader, nullptr, 0);
				context->VSSetConstantBuffers(0, 1, &transformBuffer);
				
				context->DrawIndexed(indexCount, 0, 0);

				swapChain->Present(1, 0);
			}

			swapChain->SetFullscreenState(false, nullptr);
			
			transformBuffer->Release();
			depthBufferView->Release();
			depthBuffer->Release();
			inputLayout->Release();
			vertexBuffer->Release();
			indexBuffer->Release();
			depthState->Release();
			rasterizerState->Release();
			vertexShader->Release();
			pixelShader->Release();
			renderTargetView->Release();
			swapChain->Release();
			context->Release();
			device->Release();
		}

		window.Destroy();
	}
}