Beispiel #1
0
RasterStates::RasterStates( ID3D11Device *pd3dDevice )
{
	HRESULT hr;

	D3D11_RASTERIZER_DESC RasterDesc;
	ZeroMemory( &RasterDesc, sizeof( D3D11_RASTERIZER_DESC ) );
	RasterDesc.FillMode = D3D11_FILL_SOLID;
	RasterDesc.CullMode = D3D11_CULL_NONE;
	RasterDesc.DepthClipEnable = TRUE;

	hr = pd3dDevice->CreateRasterizerState(&RasterDesc, &pRasterizerStates_[RASTERIZER_STATE::SOLID]);
	if( hr != S_OK )
	{
		return;
	}
	DXUT_SetDebugName(pRasterizerStates_[RASTERIZER_STATE::SOLID], "Solid");

	RasterDesc.FillMode = D3D11_FILL_WIREFRAME;
	hr = pd3dDevice->CreateRasterizerState(&RasterDesc, &pRasterizerStates_[RASTERIZER_STATE::WIREFRAME]);
	if( hr != S_OK )
	{
		return;
	}
	DXUT_SetDebugName(pRasterizerStates_[RASTERIZER_STATE::WIREFRAME], "Wireframe");
}
Beispiel #2
0
SamplerStates::SamplerStates(ID3D11Device *pd3dDevice)
{
	HRESULT hr;

	// Point
	D3D11_SAMPLER_DESC SamDesc;
	SamDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
	SamDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER;
	SamDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER;
	SamDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER;
	SamDesc.MipLODBias = 0.0f;
	SamDesc.MaxAnisotropy = 1;
	SamDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
	SamDesc.BorderColor[0] = SamDesc.BorderColor[1] = SamDesc.BorderColor[2] = SamDesc.BorderColor[3] = 1.0;
	SamDesc.MinLOD = 0;
	SamDesc.MaxLOD = D3D11_FLOAT32_MAX;
	V(pd3dDevice->CreateSamplerState(&SamDesc, &pSamplerStates_[SAMPLER_STATE::POINT]));
	DXUT_SetDebugName(pSamplerStates_[SAMPLER_STATE::POINT], "Point");

	// Linear
	SamDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	SamDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	SamDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	SamDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	V(pd3dDevice->CreateSamplerState(&SamDesc, &pSamplerStates_[SAMPLER_STATE::LINEAR]));
	DXUT_SetDebugName(pSamplerStates_[SAMPLER_STATE::LINEAR], "Linear");

}
void CloudShader::createBuffers(ID3D11Device* pd3dDevice)
{
	// Create the 3 constant buffers, using the same buffer descriptor to create all three
	D3D11_BUFFER_DESC Desc;
	ZeroMemory(&Desc, sizeof(Desc));
	Desc.Usage = D3D11_USAGE_DEFAULT;
	Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	Desc.CPUAccessFlags = 0;
	Desc.MiscFlags = 0;

	Desc.ByteWidth = sizeof(CB_VS_PER_OBJECT);
	pd3dDevice->CreateBuffer(&Desc, NULL, &cbVSPerObject);
	DXUT_SetDebugName(cbVSPerObject, "CB_VS_PER_OBJECT_CLOUD");

	Desc.ByteWidth = sizeof(CB_PS_PER_OBJECT);
	pd3dDevice->CreateBuffer(&Desc, NULL, &cbPSPerObject);
	DXUT_SetDebugName(cbPSPerObject, "CB_PS_PER_OBJECT_CLOUD");

	// also initialize the wind textures
	D3DX11CreateShaderResourceViewFromFile(pd3dDevice,
		L"Media\\Grass\\Wind1.png",
		NULL, NULL,
		&txWind1,
		NULL);
	DXUT_SetDebugName(txWind1, "TEX_WIND1_CLOUD");

	D3DX11CreateShaderResourceViewFromFile(pd3dDevice,
		L"Media\\Grass\\Wind2.png",
		NULL, NULL,
		&txWind2,
		NULL);
	DXUT_SetDebugName(txWind2, "TEX_WIND2_CLOUD");
}
//-------------------------------------------------------------------------------------------------
HRESULT ClearView::Init(ID3D11Device* pd3dDevice, ApplicationContext *pContext)
{
	HRESULT hr = S_OK;
	m_pContext = pContext;

	// Define screen quad vertex layout
	D3D11_INPUT_ELEMENT_DESC QuadVertexLayout[] =
	{
		{ "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 },
	};

	// Color VS
	m_pContext->m_ShaderCache.AddShader((ID3D11DeviceChild**)&m_pColorVS, AMD::ShaderCache::SHADER_TYPE_VERTEX, L"vs_5_0", L"VSColor",
		L"Shaders\\Source\\Color.hlsl", 0, NULL, &m_pColorVertexLayout, (D3D11_INPUT_ELEMENT_DESC*)QuadVertexLayout, ARRAYSIZE(QuadVertexLayout));
	// Color PS
	m_pContext->m_ShaderCache.AddShader((ID3D11DeviceChild**)&m_pColorPS, AMD::ShaderCache::SHADER_TYPE_PIXEL, L"ps_5_0", L"PSColor",
		L"Shaders\\Source\\Color.hlsl", 0, NULL, NULL, NULL, 0);

	D3D11_BUFFER_DESC Desc;

	// Utility
	Desc.Usage = D3D11_USAGE_DYNAMIC;
	Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	Desc.MiscFlags = 0;

	Desc.ByteWidth = sizeof(CB_PS_COLOR);
	V_RETURN(pd3dDevice->CreateBuffer(&Desc, nullptr, &m_pcbPSColor));
	DXUT_SetDebugName(m_pcbPSColor, "CB_PS_COLOR");

	// Fill out a unit quad
	QuadVertex QuadVertices[6];
	QuadVertices[0].v3Pos = XMFLOAT3(-1.0f, -1.0f, 0.5f);
	QuadVertices[0].v2TexCoord = XMFLOAT2(0.0f, 1.0f);
	QuadVertices[1].v3Pos = XMFLOAT3(-1.0f, 1.0f, 0.5f);
	QuadVertices[1].v2TexCoord = XMFLOAT2(0.0f, 0.0f);
	QuadVertices[2].v3Pos = XMFLOAT3(1.0f, -1.0f, 0.5f);
	QuadVertices[2].v2TexCoord = XMFLOAT2(1.0f, 1.0f);
	QuadVertices[3].v3Pos = XMFLOAT3(-1.0f, 1.0f, 0.5f);
	QuadVertices[3].v2TexCoord = XMFLOAT2(0.0f, 0.0f);
	QuadVertices[4].v3Pos = XMFLOAT3(1.0f, 1.0f, 0.5f);
	QuadVertices[4].v2TexCoord = XMFLOAT2(1.0f, 0.0f);
	QuadVertices[5].v3Pos = XMFLOAT3(1.0f, -1.0f, 0.5f);
	QuadVertices[5].v2TexCoord = XMFLOAT2(1.0f, 1.0f);

	// Create the vertex buffer
	D3D11_BUFFER_DESC BD;
	BD.Usage = D3D11_USAGE_DYNAMIC;
	BD.ByteWidth = sizeof(QuadVertex) * 6;
	BD.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	BD.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	BD.MiscFlags = 0;
	D3D11_SUBRESOURCE_DATA InitData;
	InitData.pSysMem = QuadVertices;
	hr = pd3dDevice->CreateBuffer(&BD, &InitData, &m_pQuadVertexBuffer);
	return S_OK;
}
void VertexAndPixelShaders::CreatePixelShader(ID3D11Device *device) {
	HRESULT hr = S_OK;
	pPixelShaderBuffer = NULL;
	V(CompileShaderFromFile(L"Tutorial 09 - Meshes Using DXUT Helper Classes_PS.hlsl", "PS_DXUTSDKMesh", "ps_5_0", &pPixelShaderBuffer));

	V(device->CreatePixelShader(pPixelShaderBuffer->GetBufferPointer(),
		pPixelShaderBuffer->GetBufferSize(), NULL, &g_pPixelShader));
	DXUT_SetDebugName(g_pPixelShader, "PS_DXUTSDKMesh");	
}
void ObjMeshInfo::specialLoad(ID3D11Device* pd3dDevice)
{
	// loads but not from file
	// this is a bit of a hack used by mesh generation stuff

	// create the texture resource
	D3DX11CreateShaderResourceViewFromFile(pd3dDevice,
		textureFilePath,
		NULL, NULL,
		&objMesh.subsets->txtr,
		NULL);
	DXUT_SetDebugName(objMesh.subsets->txtr, "GENERATED_MESH_TEXTURE");

	// Create the vertex buffer
	D3D11_BUFFER_DESC bd;
	ZeroMemory(&bd, sizeof(bd));
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof(SimpleVertex) * objMesh.numVertices;
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = 0;
	D3D11_SUBRESOURCE_DATA InitData;
	ZeroMemory(&InitData, sizeof(InitData));
	InitData.pSysMem = objMesh.vertices;

	pd3dDevice->CreateBuffer(&bd, &InitData, &objMesh.vb);
	DXUT_SetDebugName(objMesh.vb, "GENERATED_VERTEX_BUFFER");


	// create the index buffer
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof(USHORT) * objMesh.numIndices;

	bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	bd.CPUAccessFlags = 0;
	InitData.pSysMem = objMesh.indexes;

	pd3dDevice->CreateBuffer(&bd, &InitData, &objMesh.ib);
	DXUT_SetDebugName(objMesh.ib, "GENERATED_INDEX_BUFFER");
}
//--------------------------------------------------------------------------------------------------------------------
void RDX11RenderHelper::RenderText(RENDER_TEXT_QUAD* pText)
{
	FillFontVertex( pText );

	ID3D11Device* pd3dDevice = GLOBAL::D3DDevice();
	ID3D11DeviceContext* pd3dImmediateContext = GLOBAL::D3DContext();

	// ensure our buffer size can hold our sprites
	UINT FontDataBytes = m_FontVertices.GetSize() * sizeof( CVertexPCT );
	if( m_FontBufferBytes < FontDataBytes )
	{
		SAFE_RELEASE( m_pFontBuffer );
		m_FontBufferBytes = FontDataBytes;

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

		pd3dDevice->CreateBuffer( &BufferDesc, NULL, &m_pFontBuffer );
		DXUT_SetDebugName( m_pFontBuffer, "FontVertexBuffer" );
	}

	D3D11_MAPPED_SUBRESOURCE MappedResource;
	if ( S_OK == pd3dImmediateContext->Map( m_pFontBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) 
	{ 
		CopyMemory( MappedResource.pData, (void*)m_FontVertices.GetData(), FontDataBytes );
		pd3dImmediateContext->Unmap(m_pFontBuffer, 0);
	}

	IShaderMgr* pShaderMgr = GLOBAL::ShaderMgr();

	pShaderMgr->SetTexture( m_pFontTexture, 0);
	GLOBAL::ShaderMgr()->Begin(SHADER_FONT_VS, SHADER_FONT_PS);

	GLOBAL::RenderStateMgr()->SetTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	GLOBAL::RenderStateMgr()->SetVertexInput(FVF_3FP_1DC_2HT);

	// Draw
	UINT Stride = sizeof( CVertexPCT );
	UINT Offset = 0;
	pd3dImmediateContext->IASetVertexBuffers( 0, 1, &m_pFontBuffer, &Stride, &Offset );
	pd3dImmediateContext->Draw( m_FontVertices.GetSize(), 0 );

	m_FontVertices.Reset();
}
// ID3D11DeviceContext *context has inbuild method called CreateInputLayout, so I chose a different name
void VertexAndPixelShaders::MakeInputLayout(ID3D11Device *device) {
	HRESULT hr = S_OK;
	const D3D11_INPUT_ELEMENT_DESC layout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};

	V(device->CreateInputLayout(layout, ARRAYSIZE(layout), pVertexShaderBuffer->GetBufferPointer(),
		pVertexShaderBuffer->GetBufferSize(), &g_pVertexLayout11));
	DXUT_SetDebugName(g_pVertexLayout11, "Primary");

	SAFE_RELEASE(pVertexShaderBuffer);
	SAFE_RELEASE(pPixelShaderBuffer);

}
Beispiel #9
0
ConstantBuffer::ConstantBuffer( UINT size, ID3D11Device *pd3dDevice )
{

	D3D11_BUFFER_DESC Desc;
	Desc.Usage = D3D11_USAGE_DYNAMIC;
	Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	Desc.MiscFlags = 0;

	Desc.ByteWidth = size;
	HRESULT hr = pd3dDevice->CreateBuffer( &Desc, NULL, &pCB_ );
	if ( hr != S_OK )
	{
		return;
	}

	DXUT_SetDebugName( pCB_, "CB_DEFAULT" );
}
//--------------------------------------------------------------------------------------------------------------------
void RDX11RenderHelper::DrawLine()
{
	UINT dataBytes = m_LineVertices.GetSize() * sizeof( CVertexPC );
	if( m_LineBufferBytes < dataBytes )
	{
		SAFE_RELEASE( m_pLineBuffer );
		m_LineBufferBytes = dataBytes;

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

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

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

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

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

	m_LineVertices.Reset();
}
bool OmniMaterial::D3DCreateDevice(ID3D11Device* d3dDevice, const DXGI_SURFACE_DESC* BackBufferSurfaceDesc)
{	

	materialVS = new VertexShader(d3dDevice, L"Shaders\\OmniMaterial.hlsl", "OmniMaterialVS");
	materialPS = new PixelShader(d3dDevice, L"Shaders\\OmniMaterial.hlsl", "OmniMaterialPS");

	if(!omniCBuffer->D3DCreateDevice(d3dDevice, BackBufferSurfaceDesc)) return false;

	// Create  mesh input layout
	// isn't there an easier and better way to do this???

	// We need the vertex shader bytecode for this... rather than try to wire that all through the
	// shader interface, just recompile the vertex shader.
	UINT shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR;
	ID3D10Blob *bytecode = 0;
	HRESULT hr = D3DX11CompileFromFile(L"Shaders\\OmniMaterial.hlsl", NULL, 0, "OmniMaterialVS", "vs_5_0", shaderFlags, 0, 0, &bytecode, 0, 0);
	if (FAILED(hr)) 
	{
		assert(false);
	}

	const D3D11_INPUT_ELEMENT_DESC layout[] =
	{
		{ "POSITION",  0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,  D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "NORMAL",    0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};

	d3dDevice->CreateInputLayout( 
		layout, ARRAYSIZE(layout), 
		bytecode->GetBufferPointer(),
		bytecode->GetBufferSize(), 
		&_InputLayout);

	bytecode->Release();

	DXUT_SetDebugName(_InputLayout, "OmniMaterial_InputLayout"); 
	return hr == S_OK;
}
bool ParallelogramGeometry::D3DCreateDevice(ID3D11Device* Device, const DXGI_SURFACE_DESC* BackBufferSurfaceDesc)
{
	_Stride = 32;
	unsigned int numVerts = 4;
	unsigned int sizeInBytes = _Stride * numVerts;

	optix::float3 normal = normalize(cross(_Offset1, _Offset2));
	VertexPosNormalTexCoord verts[] =
	{		
		VertexPosNormalTexCoord(_Anchor, normal, optix::make_float2(0,0)),
		VertexPosNormalTexCoord(_Anchor + _Offset1, normal, optix::make_float2(0,1)),
		VertexPosNormalTexCoord(_Anchor + _Offset2, normal, optix::make_float2(1,0)),
		VertexPosNormalTexCoord(_Anchor + _Offset1 + _Offset2, normal, optix::make_float2(1,1))
	};

	D3D11_BUFFER_DESC desc;
	ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC));
	desc.Usage = D3D11_USAGE_DEFAULT;
	desc.ByteWidth = sizeInBytes;
	desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	desc.CPUAccessFlags = 0;
	desc.MiscFlags = 0;	

	D3D11_SUBRESOURCE_DATA init;
	ZeroMemory(&init, sizeof(D3D11_SUBRESOURCE_DATA));
	init.pSysMem = verts;
	
	if (S_OK != Device->CreateBuffer(&desc, &init, &_VertexBuffer))		
		return false;

	DXUT_SetDebugName(_VertexBuffer, "Parallelogram_VB");

	_NumElements = numVerts;
	_Topology = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
	
	return true;
}
Beispiel #13
0
void RenderableTexture::SetDebugName(char* s)
{
	DXUT_SetDebugName(m_ShaderResource, s);
	DXUT_SetDebugName(m_RenderTarget, s);
	DXUT_SetDebugName(m_Texture, s);
}
    void RSMRenderer::OnCreateDevice( ID3D11Device* pd3dDevice )
    {
        HRESULT hr;

        int width = gRSMSpotResolution * MAX_NUM_SHADOWCASTING_SPOTS;
        int height = gRSMSpotResolution;
        V( AMD::CreateDepthStencilSurface( &m_SpotAtlas.m_pDepthTexture, &m_SpotAtlas.m_pDepthSRV, &m_SpotAtlas.m_pDepthDSV, DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, width, height, 1 ) );
        V( AMD::CreateSurface( &m_SpotAtlas.m_pNormalTexture, &m_SpotAtlas.m_pNormalSRV, &m_SpotAtlas.m_pNormalRTV, 0, DXGI_FORMAT_R11G11B10_FLOAT, width, height, 1 ) );
        V( AMD::CreateSurface( &m_SpotAtlas.m_pDiffuseTexture, &m_SpotAtlas.m_pDiffuseSRV, &m_SpotAtlas.m_pDiffuseRTV, 0, DXGI_FORMAT_R11G11B10_FLOAT, width, height, 1 ) );
        int maxVPLs = width * height;

        width = gRSMPointResolution * 6;
        height = gRSMPointResolution * MAX_NUM_SHADOWCASTING_POINTS;
        V( AMD::CreateDepthStencilSurface( &m_PointAtlas.m_pDepthTexture, &m_PointAtlas.m_pDepthSRV, &m_PointAtlas.m_pDepthDSV, DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, width, height, 1 ) );
        V( AMD::CreateSurface( &m_PointAtlas.m_pNormalTexture, &m_PointAtlas.m_pNormalSRV, &m_PointAtlas.m_pNormalRTV, 0, DXGI_FORMAT_R11G11B10_FLOAT, width, height, 1 ) );
        V( AMD::CreateSurface( &m_PointAtlas.m_pDiffuseTexture, &m_PointAtlas.m_pDiffuseSRV, &m_PointAtlas.m_pDiffuseRTV, 0, DXGI_FORMAT_R11G11B10_FLOAT, width, height, 1 ) );
        maxVPLs += width * height;

        D3D11_BUFFER_DESC desc;

        ZeroMemory( &desc, sizeof( desc ) );
        desc.Usage = D3D11_USAGE_DEFAULT;
        desc.StructureByteStride = 16;
        desc.ByteWidth = desc.StructureByteStride * maxVPLs;
        desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
        desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;

        V( pd3dDevice->CreateBuffer( &desc, 0, &m_pVPLBufferCenterAndRadius ) );
        DXUT_SetDebugName( m_pVPLBufferCenterAndRadius, "VPLBufferCenterAndRadius" );

        // see struct VPLData in CommonHeader.h
        desc.StructureByteStride = 48;
        desc.ByteWidth = desc.StructureByteStride * maxVPLs;
        V( pd3dDevice->CreateBuffer( &desc, 0, &m_pVPLBufferData ) );
        DXUT_SetDebugName( m_pVPLBufferData, "VPLBufferData" );

        D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
        ZeroMemory( &SRVDesc, sizeof( SRVDesc ) );
        SRVDesc.Format = DXGI_FORMAT_UNKNOWN;
        SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
        SRVDesc.Buffer.ElementOffset = 0;
        SRVDesc.Buffer.ElementWidth = maxVPLs;
        V( pd3dDevice->CreateShaderResourceView( m_pVPLBufferCenterAndRadius, &SRVDesc, &m_pVPLBufferCenterAndRadiusSRV ) );
        V( pd3dDevice->CreateShaderResourceView( m_pVPLBufferData, &SRVDesc, &m_pVPLBufferDataSRV ) );

        D3D11_UNORDERED_ACCESS_VIEW_DESC UAVDesc;
        UAVDesc.Format = SRVDesc.Format;
        UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
        UAVDesc.Buffer.FirstElement = 0;
        UAVDesc.Buffer.NumElements = maxVPLs;
        UAVDesc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_COUNTER;
        V( pd3dDevice->CreateUnorderedAccessView( m_pVPLBufferCenterAndRadius, &UAVDesc, &m_pVPLBufferCenterAndRadiusUAV ) );
        V( pd3dDevice->CreateUnorderedAccessView( m_pVPLBufferData, &UAVDesc, &m_pVPLBufferDataUAV ) );

        desc.Usage = D3D11_USAGE_DYNAMIC;
        desc.StructureByteStride = 16*4;
        desc.ByteWidth = desc.StructureByteStride * MAX_NUM_SHADOWCASTING_SPOTS;
        desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
        desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
        V( pd3dDevice->CreateBuffer( &desc, 0, &m_pSpotInvViewProjBuffer ) );
        DXUT_SetDebugName( m_pSpotInvViewProjBuffer, "SpotInvViewProjBuffer" );

        SRVDesc.Buffer.ElementWidth = MAX_NUM_SHADOWCASTING_SPOTS;
        V( pd3dDevice->CreateShaderResourceView( m_pSpotInvViewProjBuffer, &SRVDesc, &m_pSpotInvViewProjBufferSRV ) );

        desc.ByteWidth = desc.StructureByteStride * MAX_NUM_SHADOWCASTING_POINTS * 6;
        V( pd3dDevice->CreateBuffer( &desc, 0, &m_pPointInvViewProjBuffer ) );
        DXUT_SetDebugName( m_pPointInvViewProjBuffer, "PointInvViewProjBuffer" );

        SRVDesc.Buffer.ElementWidth = 6*MAX_NUM_SHADOWCASTING_POINTS;
        V( pd3dDevice->CreateShaderResourceView( m_pPointInvViewProjBuffer, &SRVDesc, &m_pPointInvViewProjBufferSRV ) );


        ZeroMemory( &desc, sizeof( desc ) );
        desc.Usage = D3D11_USAGE_DEFAULT;
        desc.ByteWidth = 16;
        desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
        V( pd3dDevice->CreateBuffer( &desc, 0, &m_pNumVPLsConstantBuffer ) );
        DXUT_SetDebugName( m_pNumVPLsConstantBuffer, "NumVPLsConstantBuffer" );

        desc.BindFlags = 0;
        desc.Usage = D3D11_USAGE_STAGING;
        desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
        V( pd3dDevice->CreateBuffer( &desc, 0, &m_pCPUReadbackConstantBuffer ) );
        DXUT_SetDebugName( m_pCPUReadbackConstantBuffer, "CPUReadbackConstantBuffer" );
    }
Beispiel #15
0
Shader::Shader( ID3D11Device *pd3dDevice, ID3D11DeviceContext *pd3dImmediateContext )
{
	vs_current_ = VS::MAX;

	// Compile shaders
	ID3DBlob* pBlobVS = NULL;
	ID3DBlob* pBlobHSInt = NULL;
	ID3DBlob* pBlobHSFracEven = NULL;
	ID3DBlob* pBlobHSFracOdd = NULL;
	ID3DBlob* pBlobDS = NULL;
	ID3DBlob* pBlobPS = NULL;
	ID3DBlob* pBlobPSSolid = NULL;

	// This macro is used to compile the hull shader with different partition modes
	// Please see the partitioning mode attribute for the hull shader for more information
	D3D_SHADER_MACRO integerPartitioning[] = { { "BEZIER_HS_PARTITION", "\"integer\"" }, { 0 } };
	D3D_SHADER_MACRO fracEvenPartitioning[] = { { "BEZIER_HS_PARTITION", "\"fractional_even\"" }, { 0 } };
	D3D_SHADER_MACRO fracOddPartitioning[] = { { "BEZIER_HS_PARTITION", "\"fractional_odd\"" }, { 0 } };

	HRESULT hr;
	V( CompileShaderFromFile( L"sample.hlsl", NULL, "BezierVS", "vs_5_0",  &pBlobVS ) );
	V( CompileShaderFromFile( L"sample.hlsl", integerPartitioning, "BezierHS", "hs_5_0", &pBlobHSInt ) );
	V( CompileShaderFromFile( L"sample.hlsl", fracEvenPartitioning, "BezierHS", "hs_5_0", &pBlobHSFracEven ) );
	V( CompileShaderFromFile( L"sample.hlsl", fracOddPartitioning, "BezierHS", "hs_5_0", &pBlobHSFracOdd ) );
	V( CompileShaderFromFile( L"sample.hlsl", NULL, "BezierDS", "ds_5_0", &pBlobDS ) );
	V( CompileShaderFromFile( L"sample.hlsl", NULL, "BezierPS", "ps_5_0", &pBlobPS ) );
	V( CompileShaderFromFile( L"sample.hlsl", NULL, "SolidColorPS", "ps_5_0", &pBlobPSSolid ) );

	// Create shaders
	V(pd3dDevice->CreateVertexShader(pBlobVS->GetBufferPointer(), pBlobVS->GetBufferSize(), NULL, &pVertexShader_[VS::BEZIER]));
	DXUT_SetDebugName(pVertexShader_[VS::BEZIER], "BezierVS");

	V(pd3dDevice->CreateHullShader(pBlobHSInt->GetBufferPointer(), pBlobHSInt->GetBufferSize(), NULL, &pHullShader_[HS::PARTITION_INTEGER]));
	DXUT_SetDebugName( pHullShader_[HS::PARTITION_INTEGER], "BezierHS int" );

	V(pd3dDevice->CreateHullShader(pBlobHSFracEven->GetBufferPointer(), pBlobHSFracEven->GetBufferSize(), NULL, &pHullShader_[HS::PARTITION_FRACTIONAL_EVEN]));
	DXUT_SetDebugName(pHullShader_[HS::PARTITION_FRACTIONAL_EVEN], "BezierHS frac even");

	V(pd3dDevice->CreateHullShader(pBlobHSFracOdd->GetBufferPointer(), pBlobHSFracOdd->GetBufferSize(), NULL, &pHullShader_[HS::PARTITION_FRACTIONAL_ODD]));
	DXUT_SetDebugName(pHullShader_[HS::PARTITION_FRACTIONAL_ODD], "BezierHS frac odd");

	V(pd3dDevice->CreateDomainShader(pBlobDS->GetBufferPointer(), pBlobDS->GetBufferSize(), NULL, &pDomainShader_[DS::BEZIER]));
	DXUT_SetDebugName(pDomainShader_[DS::BEZIER], "BezierDS");

	V(pd3dDevice->CreatePixelShader(pBlobPS->GetBufferPointer(), pBlobPS->GetBufferSize(), NULL, &pPixelShader_[PS::BEZIER]));
	DXUT_SetDebugName(pPixelShader_[PS::BEZIER], "BezierPS");

	V(pd3dDevice->CreatePixelShader(pBlobPSSolid->GetBufferPointer(), pBlobPSSolid->GetBufferSize(), NULL, &pPixelShader_[PS::SOLID_COLOR]));
	DXUT_SetDebugName(pPixelShader_[PS::SOLID_COLOR], "SolidColorPS");

	// Create our vertex input layout - this matches the BEZIER_CONTROL_POINT structure
	const D3D11_INPUT_ELEMENT_DESC layout_BEZIER[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,  D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};

	V(pd3dDevice->CreateInputLayout(layout_BEZIER, ARRAYSIZE(layout_BEZIER), pBlobVS->GetBufferPointer(),
		pBlobVS->GetBufferSize(), &pLayout_[VS::BEZIER]));
	DXUT_SetDebugName(pLayout_[VS::BEZIER], "Primary");

	SAFE_RELEASE( pBlobVS );
	SAFE_RELEASE( pBlobHSInt );
	SAFE_RELEASE( pBlobHSFracEven );
	SAFE_RELEASE( pBlobHSFracOdd );
	SAFE_RELEASE( pBlobDS );
	SAFE_RELEASE( pBlobPS );
	SAFE_RELEASE( pBlobPSSolid );

	pCB_[VS::BEZIER] = new ConstantBuffer(sizeof(CB_BEZIER), pd3dDevice);

	// Render Scene
	V(CompileShaderFromFile(L"scene.hlsl", NULL, "VS_RenderScene", "vs_5_0", &pBlobVS));
	V(CompileShaderFromFile(L"scene.hlsl", NULL, "PS_RenderScene", "ps_5_0", &pBlobPS));
	V(pd3dDevice->CreateVertexShader(pBlobVS->GetBufferPointer(), pBlobVS->GetBufferSize(), NULL, &pVertexShader_[VS::SCENE]));
	DXUT_SetDebugName(pVertexShader_[VS::SCENE], "SceneVS");
	V(pd3dDevice->CreatePixelShader(pBlobPS->GetBufferPointer(), pBlobPS->GetBufferSize(), NULL, &pPixelShader_[PS::SCENE]));
	DXUT_SetDebugName(pPixelShader_[PS::SCENE], "ScenePS");

	const D3D11_INPUT_ELEMENT_DESC SceneLayout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};
	hr = pd3dDevice->CreateInputLayout(SceneLayout, ARRAYSIZE(SceneLayout), pBlobVS->GetBufferPointer(),
		pBlobVS->GetBufferSize(), &pLayout_[VS::SCENE]);
	DXUT_SetDebugName(pLayout_[VS::SCENE], "SceneLayout");

	SAFE_RELEASE(pBlobVS);
	SAFE_RELEASE(pBlobPS);

	pCB_[VS::SCENE] = new ConstantBuffer(sizeof(CB_SCENE), pd3dDevice);

	// Render Decal
	V(CompileShaderFromFile(L"decal.hlsl", NULL, "VS", "vs_5_0", &pBlobVS));
	V(CompileShaderFromFile(L"decal.hlsl", NULL, "PS", "ps_5_0", &pBlobPS));
	V(pd3dDevice->CreateVertexShader(pBlobVS->GetBufferPointer(), pBlobVS->GetBufferSize(), NULL, &pVertexShader_[VS::DECAL]));
	DXUT_SetDebugName(pVertexShader_[VS::DECAL], "DecalVS");
	V(pd3dDevice->CreatePixelShader(pBlobPS->GetBufferPointer(), pBlobPS->GetBufferSize(), NULL, &pPixelShader_[PS::DECAL]));
	DXUT_SetDebugName(pPixelShader_[PS::DECAL], "DecalPS");

	const D3D11_INPUT_ELEMENT_DESC DecalLayout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};
	hr = pd3dDevice->CreateInputLayout(DecalLayout, ARRAYSIZE(DecalLayout), pBlobVS->GetBufferPointer(),
		pBlobVS->GetBufferSize(), &pLayout_[VS::DECAL]);
	DXUT_SetDebugName(pLayout_[VS::DECAL], "DecalLayout");

	SAFE_RELEASE(pBlobVS);
	SAFE_RELEASE(pBlobPS);

	pCB_[VS::DECAL] = new ConstantBuffer(sizeof(CB_DECAL), pd3dDevice);

	// Render Shadow maps
	V(CompileShaderFromFile(L"shadow.hlsl", NULL, "VSMain", "vs_5_0", &pBlobVS));
	V(CompileShaderFromFile(L"shadow.hlsl", NULL, "PSMain", "ps_5_0", &pBlobPS));
	V(pd3dDevice->CreateVertexShader(pBlobVS->GetBufferPointer(), pBlobVS->GetBufferSize(), NULL, &pVertexShader_[VS::SHADOW]));
	DXUT_SetDebugName(pVertexShader_[VS::SHADOW], "ShadowVS");
	V(pd3dDevice->CreatePixelShader(pBlobPS->GetBufferPointer(), pBlobPS->GetBufferSize(), NULL, &pPixelShader_[PS::SHADOW]));
	DXUT_SetDebugName(pPixelShader_[PS::SHADOW], "ShadowPS");

	const D3D11_INPUT_ELEMENT_DESC LayoutShadow[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};
	hr = pd3dDevice->CreateInputLayout(LayoutShadow, ARRAYSIZE(LayoutShadow), pBlobVS->GetBufferPointer(),
		pBlobVS->GetBufferSize(), &pLayout_[VS::SHADOW]);
	DXUT_SetDebugName(pLayout_[VS::SHADOW], "ShadowLayout");

	SAFE_RELEASE(pBlobVS);
	SAFE_RELEASE(pBlobPS);

	pCB_[VS::SHADOW] = new ConstantBuffer(sizeof(CB_SHADOW), pd3dDevice);

	// TAA
	V(CompileShaderFromFile(L"taa.hlsl", NULL, "VS", "vs_5_0", &pBlobVS));
	V(CompileShaderFromFile(L"taa.hlsl", NULL, "PS", "ps_5_0", &pBlobPS));
	V(pd3dDevice->CreateVertexShader(pBlobVS->GetBufferPointer(), pBlobVS->GetBufferSize(), NULL, &pVertexShader_[VS::TAA]));
	DXUT_SetDebugName(pVertexShader_[VS::TAA], "TAA VS");
	V(pd3dDevice->CreatePixelShader(pBlobPS->GetBufferPointer(), pBlobPS->GetBufferSize(), NULL, &pPixelShader_[PS::TAA]));
	DXUT_SetDebugName(pPixelShader_[PS::TAA], "TAA PS");

	const D3D11_INPUT_ELEMENT_DESC LayoutTaa[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};
	hr = pd3dDevice->CreateInputLayout(LayoutTaa, ARRAYSIZE(LayoutTaa), pBlobVS->GetBufferPointer(),
		pBlobVS->GetBufferSize(), &pLayout_[VS::TAA]);
	DXUT_SetDebugName(pLayout_[VS::TAA], "TAA Layout");

	SAFE_RELEASE(pBlobVS);
	SAFE_RELEASE(pBlobPS);

	pCB_[VS::TAA] = new ConstantBuffer(sizeof(CB_TAA), pd3dDevice);
}
bool SphereGeometry::D3DCreateDevice(ID3D11Device* Device, const DXGI_SURFACE_DESC* BackBufferSurfaceDesc)
{
	int Slices = 20;
	int Stacks = 15;
	if (Slices < 3)
        Slices = 3;
    if (Stacks < 2)
        Stacks = 2;            

    int numVertices = (Stacks + 1) * (Slices + 1);
    int numIndices = 6 * Stacks * (Slices + 1);

	bool useShort = numIndices < SHRT_MAX;

	int floatsPerVert = 3*2; // float3 * 2 (pos, normal)
	int sizeInBytes = numVertices * floatsPerVert * sizeof(float);
    float* verts = new float[numVertices * floatsPerVert]; 
    int* indices = NULL; 
    short* indices16 = NULL;
    if (useShort)
        indices16 = new short[numIndices];
    else
        indices = new int[numIndices];            

	float deltaRingAngle = (float)D3DX_PI / Stacks;
    float deltaSegmentAngle = 2.0f * (float)D3DX_PI / Slices;

    // Generate the group of rings for the sphere
    int vertexIndex = 0;
    int indexIndex = 0;
    for (int i = 0; i <= Stacks; i++)
    {
		float ring = sinf(i * deltaRingAngle);
        float y = cosf(i * deltaRingAngle);

        // Generate the group of segments for the current ring
        for (int j = 0; j <= Slices; j++)
        {
            float x = ring * sinf(j * deltaSegmentAngle);
            float z = ring * cosf(j * deltaSegmentAngle);

            // Add one vertex to the strip which makes up the sphere
            optix::float3 position = optix::make_float3(x, y, z);
			optix::float3 normal = optix::normalize(position);
    //        float2 textureCoordinate = make_float2((float)j / Slices, (float)i / Stacks);

			verts[vertexIndex * floatsPerVert + 0] = position.x * _Radius + _Center.x;
			verts[vertexIndex * floatsPerVert + 1] = position.y * _Radius + _Center.y;
			verts[vertexIndex * floatsPerVert + 2] = position.z * _Radius + _Center.z;
			verts[vertexIndex * floatsPerVert + 3] = normal.x;
			verts[vertexIndex * floatsPerVert + 4] = normal.y;
			verts[vertexIndex * floatsPerVert + 5] = normal.z;

            if (i != Stacks)
            {
                if (useShort)
                {
                    // each vertex (except the last) has six indices pointing to it
                    indices16[indexIndex++] = (short)(vertexIndex + Slices);
					indices16[indexIndex++] = (short)(vertexIndex + Slices + 1);
                    indices16[indexIndex++] = (short)(vertexIndex);
                    
                    indices16[indexIndex++] = (short)(vertexIndex);
					indices16[indexIndex++] = (short)(vertexIndex + Slices + 1);
                    indices16[indexIndex++] = (short)(vertexIndex + 1);
                    
                }
                else
                {
                    // each vertex (except the last) has six indices pointing to it
                    indices[indexIndex++] = vertexIndex + Slices;
					indices[indexIndex++] = vertexIndex + Slices + 1;
                    indices[indexIndex++] = vertexIndex;

                    indices[indexIndex++] = vertexIndex;
					indices[indexIndex++] = vertexIndex + Slices + 1;
                    indices[indexIndex++] = vertexIndex + 1;
                    
                }
            }

            vertexIndex++;
        }
    }

	_Stride = 24;

	D3D11_BUFFER_DESC desc;
	ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC));
	desc.Usage = D3D11_USAGE_DEFAULT;
	desc.ByteWidth = sizeInBytes;
	desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	desc.CPUAccessFlags = 0;
	desc.MiscFlags = 0;	

	D3D11_SUBRESOURCE_DATA init;
	ZeroMemory(&init, sizeof(D3D11_SUBRESOURCE_DATA));
	init.pSysMem = verts;
	
	if (S_OK != Device->CreateBuffer(&desc, &init, &_VertexBuffer))
	{
		SAFE_DELETE_ARRAY(verts);
		SAFE_DELETE_ARRAY(indices);
		SAFE_DELETE_ARRAY(indices16);
		return false;
	}

	DXUT_SetDebugName(_VertexBuffer, "Sphere_VB");

	ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC));
	desc.Usage = D3D11_USAGE_DEFAULT;
	desc.ByteWidth = numIndices * ( useShort ? sizeof(short) : sizeof(int) );
	desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	desc.CPUAccessFlags = 0;
	desc.MiscFlags = 0;		
	
	ZeroMemory(&init, sizeof(D3D11_SUBRESOURCE_DATA));
	init.pSysMem = useShort ? (void*)indices16 : (void*)indices;
	
	if (S_OK != Device->CreateBuffer(&desc, &init, &_IndexBuffer))
	{
		SAFE_DELETE_ARRAY(verts);
		SAFE_DELETE_ARRAY(indices);
		SAFE_DELETE_ARRAY(indices16);
		return false;
	}
	DXUT_SetDebugName(_IndexBuffer, "Sphere_IB");

	SAFE_DELETE_ARRAY(verts);
	SAFE_DELETE_ARRAY(indices);
	SAFE_DELETE_ARRAY(indices16);

	_IndexFormat = useShort ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
	_NumElements = numIndices;
	_Topology = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
	
	return true; 
}
//--------------------------------------------------------------------------------------
// Create any D3D11 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
                                      void* pUserContext )
{
    HRESULT hr;

    ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext();
    V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) );
    V_RETURN( g_D3DSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) );
    g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 );
    g_pTxtHelper1 = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 35 );

    // textures / rts
    D3D11_TEXTURE2D_DESC TDesc;
      
    TDesc.Width  = UINT(g_fShadowMapWidth);
    TDesc.Height = UINT(g_fShadowMapHeight);
    TDesc.MipLevels = 1;
    TDesc.ArraySize = 1;
    TDesc.Format = DXGI_FORMAT_R16_TYPELESS;
    TDesc.SampleDesc.Count = 1;
    TDesc.SampleDesc.Quality = 0;
    TDesc.Usage = D3D11_USAGE_DEFAULT;
    TDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
    TDesc.CPUAccessFlags = 0;
    TDesc.MiscFlags = 0;
    pd3dDevice->CreateTexture2D( &TDesc, 0, &g_pRSMDepthStencilTexture);
    DXUT_SetDebugName( g_pRSMDepthStencilTexture, "RSM" );

    D3D11_DEPTH_STENCIL_VIEW_DESC DSVDesc;
    
    DSVDesc.Format = DXGI_FORMAT_D16_UNORM;
    DSVDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    DSVDesc.Flags = 0;
    DSVDesc.Texture2D.MipSlice = 0;
    pd3dDevice->CreateDepthStencilView( g_pRSMDepthStencilTexture, &DSVDesc, & g_pDepthStencilTextureDSV );
    DXUT_SetDebugName( g_pDepthStencilTextureDSV, "RSM DSV" );

    D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
    
    SRVDesc.Format =  DXGI_FORMAT_R16_UNORM;
    SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    SRVDesc.Texture2D.MipLevels = 1;
    SRVDesc.Texture2D.MostDetailedMip = 0;
    pd3dDevice->CreateShaderResourceView( g_pRSMDepthStencilTexture, &SRVDesc, &g_pDepthTextureSRV );
    DXUT_SetDebugName( g_pDepthTextureSRV, "RSM SRV" );

    // Setup constant buffers
    D3D11_BUFFER_DESC Desc;
    
    // Utility
    Desc.Usage = D3D11_USAGE_DYNAMIC;
    Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    Desc.MiscFlags = 0;    
    Desc.ByteWidth = sizeof( CB_CONSTANTS );
    V_RETURN( pd3dDevice->CreateBuffer( &Desc, NULL, &g_pcbConstants ) );
    DXUT_SetDebugName( g_pcbConstants, "CB_CONSTANTS"  );

    // Load the scene mesh
    WCHAR str[256];
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, 256,  L"ColumnScene\\scene.sdkmesh" ) );
    g_SceneMesh.Create( pd3dDevice, str, false );

    V_RETURN( DXUTFindDXSDKMediaFileCch( str, 256,  L"ColumnScene\\poles.sdkmesh" ) );
    g_Poles.Create( pd3dDevice, str, false );

    // Setup the camera   
    D3DXVECTOR3 vecEye( 0.95f, 5.83f, -14.48f );
    D3DXVECTOR3 vecAt ( 0.90f, 5.44f, -13.56f );
    g_Camera.SetViewParams( &vecEye, &vecAt );
    D3DXVECTOR3 vecEyeL = D3DXVECTOR3( 0,0,0 );
    D3DXVECTOR3 vecAtL ( 0, -0.5, 1 );
    g_LCamera.SetViewParams( &vecEyeL, &vecAtL );

    // Create sampler states for point and linear

    // PointCmp
    D3D11_SAMPLER_DESC SamDesc;
    SamDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT;
    SamDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER;
    SamDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER;
    SamDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER;
    SamDesc.MipLODBias = 0.0f;
    SamDesc.MaxAnisotropy = 1;
    SamDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL;
    SamDesc.BorderColor[0] = SamDesc.BorderColor[1] = SamDesc.BorderColor[2] = SamDesc.BorderColor[3] = 1.0;
    SamDesc.MinLOD = 0;
    SamDesc.MaxLOD = D3D11_FLOAT32_MAX;
    V_RETURN( pd3dDevice->CreateSamplerState( &SamDesc, &g_pSamplePointCmp ) );
    DXUT_SetDebugName( g_pSamplePointCmp, "PointCmp" );

    // Point
    SamDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
    SamDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    V_RETURN( pd3dDevice->CreateSamplerState( &SamDesc, &g_pSamplePoint ) );
    DXUT_SetDebugName( g_pSamplePoint, "Point" );

    // Linear
    SamDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    SamDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    SamDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    SamDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    V_RETURN( pd3dDevice->CreateSamplerState( &SamDesc, &g_pSampleLinear ) );
    DXUT_SetDebugName( g_pSampleLinear, "Linear" );

    // Create a blend state to disable alpha blending
    D3D11_BLEND_DESC BlendState;
    ZeroMemory(&BlendState, sizeof(D3D11_BLEND_DESC));
    BlendState.IndependentBlendEnable = FALSE;
    BlendState.RenderTarget[0].BlendEnable = FALSE;
    BlendState.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
    hr = pd3dDevice->CreateBlendState(&BlendState, &g_pBlendStateNoBlend);
    DXUT_SetDebugName( g_pBlendStateNoBlend, "No Blend" );
    
    BlendState.RenderTarget[0].RenderTargetWriteMask = 0;
    hr = pd3dDevice->CreateBlendState(&BlendState, &g_pBlendStateColorWritesOff);
    DXUT_SetDebugName( g_pBlendStateColorWritesOff, "Color Writes Off");

    return S_OK;
}
Beispiel #18
0
//--------------------------------------------------------------------------------------
// FillGrid_Indexed_WithTangentSpace
// Creates a regular grid of indexed triangles
// Includes tangent space vectors: NORMAL, TANGENT & BINORMAL
//
// Parameters:
//
// IN
// pd3dDevice:                   The D3D device
// dwWidth, dwLength:            Number of grid vertices in X and Z direction
// fGridSizeX, fGridSizeZ:       Grid extents in local space units
//
// OUT
// lplpVB:                       A pointer to the vertex buffer containing grid vertices
// lplpIB:                       A pointer to the index buffer containing grid indices
//--------------------------------------------------------------------------------------
void FillGrid_Indexed_WithTangentSpace( ID3D11Device* pd3dDevice, DWORD dwWidth, DWORD dwLength, 
                                        float fGridSizeX, float fGridSizeZ, 
                                        ID3D11Buffer** lplpVB, ID3D11Buffer** lplpIB )
{
    HRESULT hr;
    DWORD   nNumVertex = ( dwWidth + 1 ) * ( dwLength + 1 );
    DWORD   nNumIndex = 3 * 2 * dwWidth * dwLength;
    float   fStepX = fGridSizeX / dwWidth;
    float   fStepZ = fGridSizeZ / dwLength;
    
    // Allocate memory for buffer of vertices in system memory
    TANGENTSPACEVERTEX*    pVertexBuffer = new TANGENTSPACEVERTEX[nNumVertex];
    TANGENTSPACEVERTEX*    pVertex = &pVertexBuffer[0];

    // Fill vertex buffer
    for ( DWORD i=0; i<=dwLength; ++i )
    {
        for ( DWORD j=0; j<=dwWidth; ++j )
        {
            pVertex->x = -fGridSizeX/2.0f + j*fStepX;
            pVertex->y = 0.0f;
            pVertex->z = fGridSizeZ/2.0f - i*fStepZ;
            pVertex->u = 0.0f + ( (float)j / dwWidth  );
            pVertex->v = 0.0f + ( (float)i / dwLength );

            // Flat grid so tangent space is very basic; with more complex geometry 
            // you would have to export calculated tangent space vectors
            pVertex->nx = 0.0f;
            pVertex->ny = 1.0f;
            pVertex->nz = 0.0f;
            pVertex->bx = 0.0f;
            pVertex->by = 0.0f;
            pVertex->bz = -1.0f;
            pVertex->tx = 1.0f;
            pVertex->ty = 0.0f;
            pVertex->tz = 0.0f;
            pVertex++;
        }
    }
    
    // Allocate memory for buffer of indices in system memory
    WORD*    pIndexBuffer = new WORD [nNumIndex];
    WORD*    pIndex = &pIndexBuffer[0];

    // Fill index buffer
    for ( DWORD i=0; i<dwLength; ++i )
    {
        for ( DWORD j=0; j<dwWidth; ++j )
        {
            *pIndex++ = (WORD)(  i    * (dwWidth+1) + j     );
            *pIndex++ = (WORD)(  i    * (dwWidth+1) + j + 1 );
            *pIndex++ = (WORD)( (i+1) * (dwWidth+1) + j     );

            *pIndex++ = (WORD)( (i+1) * (dwWidth+1) + j     );
            *pIndex++ = (WORD)(  i    * (dwWidth+1) + j + 1 );
            *pIndex++ = (WORD)( (i+1) * (dwWidth+1) + j + 1 );
        }
    }

#ifdef GRID_OPTIMIZE_INDICES
    GridOptimizeIndices(pIndexBuffer, nNumIndex, nNumVertex);
#endif

#ifdef GRID_OPTIMIZE_VERTICES
    GridOptimizeVertices(pIndexBuffer, pVertexBuffer, sizeof(TANGENTSPACEVERTEX), 
                         nNumIndex, nNumVertex);
#endif


    // Actual VB creation

    // Set initial data info
    D3D11_SUBRESOURCE_DATA InitData;
    InitData.pSysMem = pVertexBuffer;

    // Fill DX11 vertex buffer description
    D3D11_BUFFER_DESC    bd;
    bd.Usage =           D3D11_USAGE_DEFAULT;
    bd.ByteWidth =       sizeof( TANGENTSPACEVERTEX ) * nNumVertex;
    bd.BindFlags =       D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags =  0;
    bd.MiscFlags =       0;

    // Create DX11 vertex buffer specifying initial data
    hr = pd3dDevice->CreateBuffer( &bd, &InitData, lplpVB );
    if( FAILED( hr ) )
    {
        OutputDebugString( L"FillGrid_Indexed_WithTangentSpace: Failed to create vertex buffer.\n" );
        return;
    }
    DXUT_SetDebugName( *lplpVB, "FillGrid VB Tan Idx" );

    // Actual IB creation

    // Set initial data info
    InitData.pSysMem = pIndexBuffer;

    // Fill DX11 vertex buffer description
    bd.ByteWidth = sizeof( WORD ) * nNumIndex;
    bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
    
    // Create DX11 index buffer specifying initial data
    hr = pd3dDevice->CreateBuffer( &bd, &InitData, lplpIB );
    if( FAILED( hr ) )
    {
        OutputDebugString( L"FillGrid_Indexed_WithTangentSpace: Failed to create index buffer.\n" );
        return;
    }
    DXUT_SetDebugName( *lplpIB, "FillGrid IB Tan" );

    // Release host memory vertex buffer
    delete [] pIndexBuffer;

    // Release host memory vertex buffer
    delete [] pVertexBuffer;
}
Beispiel #19
0
//--------------------------------------------------------------------------------------
// FillGrid_Quads_NonIndexed
// Creates a regular grid using non-indexed quads.
//
// Parameters:
//
// IN
// pd3dDevice:                The D3D device
// dwWidth, dwLength:         Number of grid vertices in X and Z direction
// fGridSizeX, fGridSizeZ:    Grid extents in local space units
//
// OUT
// lplpVB:                    A pointer to the vertex buffer containing grid vertices
//
//--------------------------------------------------------------------------------------
void FillGrid_Quads_NonIndexed( ID3D11Device* pd3dDevice, DWORD dwWidth, DWORD dwLength, 
                                float fGridSizeX, float fGridSizeZ, 
                                ID3D11Buffer** lplpVB )
{
    HRESULT  hr;
    DWORD    nNumQuads = dwWidth * dwLength;
    DWORD    nNumVertex = 4 * nNumQuads;
    float    fStepX = fGridSizeX / dwWidth;
    float    fStepZ = fGridSizeZ / dwLength;
    
    // Allocate memory for buffer of vertices in system memory
    SIMPLEVERTEX*    pVertexBuffer = new SIMPLEVERTEX[nNumVertex];
    SIMPLEVERTEX*    pVertex = &pVertexBuffer[0];

    for ( DWORD i=0; i<dwLength; ++i )
    {
        for ( DWORD j=0; j<dwWidth; ++j )
        {
            // Vertex 0
            pVertex->x = -fGridSizeX/2.0f + j*fStepX;
            pVertex->y = 0.0f;
            pVertex->z = fGridSizeZ/2.0f - i*fStepZ;
            pVertex->u = 0.0f + ( (float)j / dwWidth  );
            pVertex->v = 0.0f + ( (float)i / dwLength );
            pVertex++;

            // Vertex 1
            pVertex->x = -fGridSizeX/2.0f + (j+1)*fStepX;
            pVertex->y = 0.0f;
            pVertex->z = fGridSizeZ/2.0f - i*fStepZ;
            pVertex->u = 0.0f + ( (float)(j+1)/ dwWidth);
            pVertex->v = 0.0f + ( (float) i   / dwLength);
            pVertex++;

            // Vertex 2
            pVertex->x = -fGridSizeX/2.0f + (j+1)*fStepX;
            pVertex->y = 0.0f;
            pVertex->z = fGridSizeZ/2.0f - (i+1)*fStepZ;
            pVertex->u = 0.0f + ( (float)(j+1) / dwWidth  );
            pVertex->v = 0.0f + ( (float)(i+1) / dwLength );
            pVertex++;

            // Vertex 3
            pVertex->x = -fGridSizeX/2.0f + j*fStepX;
            pVertex->y = 0.0f;
            pVertex->z = fGridSizeZ/2.0f - (i+1)*fStepZ;
            pVertex->u = 0.0f + ( (float) j   / dwWidth );
            pVertex->v = 0.0f + ( (float)(i+1)/ dwLength );
            pVertex++;
        }
    }
    
    // Set initial data info
    D3D11_SUBRESOURCE_DATA InitData;
    InitData.pSysMem = pVertexBuffer;

    // Fill DX11 vertex buffer description
    D3D11_BUFFER_DESC    bd;
    bd.Usage =           D3D11_USAGE_DEFAULT;
    bd.ByteWidth =       sizeof( SIMPLEVERTEX ) * nNumVertex;
    bd.BindFlags =       D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags =  0;
    bd.MiscFlags =       0;

    // Create DX11 vertex buffer specifying initial data
    hr = pd3dDevice->CreateBuffer( &bd, &InitData, lplpVB );
    if( FAILED( hr ) )
    {
        OutputDebugString( L"FillGrid_Quads_NonIndexed: Failed to create vertex buffer.\n" );
        return;
    }
    DXUT_SetDebugName( *lplpVB, "FillGrid VB Quads" );

    // Release host memory vertex buffer
    delete [] pVertexBuffer;
}
//--------------------------------------------------------------------------------------
// Create any D3D11 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
                                     void* pUserContext )
{
    DXUT_SetDebugName( pd3dDevice, "Main Device" );

    HRESULT hr;

    ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext();
    V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) );
    V_RETURN( g_SettingsDlg.OnD3D11CreateDevice( pd3dDevice ) );
    g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 );

    IDXGIDevice* pDXGIDevice;
    hr = pd3dDevice->QueryInterface( __uuidof(IDXGIDevice), (VOID**)&pDXGIDevice );
    if( SUCCEEDED(hr) )
    {
        IDXGIAdapter* pAdapter;
        hr = pDXGIDevice->GetAdapter( &pAdapter );
        if( SUCCEEDED(hr) )
        {
            DXGI_ADAPTER_DESC AdapterDesc;
            pAdapter->GetDesc( &AdapterDesc );
            SetAdapterInfoForShaderCompilation( AdapterDesc.Description );
            SAFE_RELEASE( pAdapter );
        }
        SAFE_RELEASE( pDXGIDevice );
    }

    ID3D10Blob* pVSBlob = NULL;
    g_pVSTransform = CompileVertexShader( pd3dDevice, L"SceneRender.hlsl", "VSTransform", &pVSBlob );
    g_pPSSceneRender = CompilePixelShader( pd3dDevice, L"SceneRender.hlsl", "PSSceneRender" );
    g_pPSSceneRenderArray = CompilePixelShader( pd3dDevice, L"SceneRender.hlsl", "PSSceneRenderArray" );
    g_pPSSceneRenderQuilt = CompilePixelShader( pd3dDevice, L"SceneRender.hlsl", "PSSceneRenderQuilt" );

    // Create a layout for the object data
    const D3D11_INPUT_ELEMENT_DESC layout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    };

    V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVSBlob->GetBufferPointer(),
                                             pVSBlob->GetBufferSize(), &g_pDefaultInputLayout ) );

    // No longer need the shader blobs
    SAFE_RELEASE( pVSBlob );

    // Create state objects
    D3D11_SAMPLER_DESC samDesc;
    ZeroMemory( &samDesc, sizeof(samDesc) );
    samDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    samDesc.AddressU = samDesc.AddressV = samDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    samDesc.MaxAnisotropy = 1;
    samDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    samDesc.MaxLOD = D3D11_FLOAT32_MAX;
    V_RETURN( pd3dDevice->CreateSamplerState( &samDesc, &g_pSamLinear ) );
    DXUT_SetDebugName( g_pSamLinear, "Linear" );

    D3D11_BLEND_DESC BlendDesc;
    ZeroMemory( &BlendDesc, sizeof( D3D11_BLEND_DESC ) );
    BlendDesc.RenderTarget[0].BlendEnable = FALSE;
    BlendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
    BlendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
    BlendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
    BlendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
    BlendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
    BlendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
    BlendDesc.RenderTarget[0].RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;
    hr = pd3dDevice->CreateBlendState( &BlendDesc, &g_pBlendState );
    ASSERT( SUCCEEDED(hr) );

    D3D11_DEPTH_STENCIL_DESC DSDesc;
    ZeroMemory( &DSDesc, sizeof(D3D11_DEPTH_STENCIL_DESC) );
    DSDesc.DepthEnable = FALSE;
    DSDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    DSDesc.DepthFunc = D3D11_COMPARISON_LESS;
    DSDesc.StencilEnable = FALSE;
    DSDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
    DSDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
    hr = pd3dDevice->CreateDepthStencilState( &DSDesc, &g_pDepthStencilState );
    ASSERT( SUCCEEDED(hr) );

    D3D11_RASTERIZER_DESC RSDesc;
    ZeroMemory( &RSDesc, sizeof(RSDesc) );
    RSDesc.AntialiasedLineEnable = FALSE;
    RSDesc.CullMode = D3D11_CULL_BACK;
    RSDesc.DepthBias = 0;
    RSDesc.DepthBiasClamp = 0.0f;
    RSDesc.DepthClipEnable = TRUE;
    RSDesc.FillMode = D3D11_FILL_SOLID;
    RSDesc.FrontCounterClockwise = FALSE;
    RSDesc.MultisampleEnable = TRUE;
    RSDesc.ScissorEnable = FALSE;
    RSDesc.SlopeScaledDepthBias = 0.0f;
    hr = pd3dDevice->CreateRasterizerState( &RSDesc, &g_pRasterizerState );
    ASSERT( SUCCEEDED(hr) );

    g_pcbVSPerObject11 = CreateConstantBuffer( pd3dDevice, sizeof(CB_VS_PER_OBJECT) );
    DXUT_SetDebugName( g_pcbVSPerObject11, "CB_VS_PER_OBJECT" );

    // Create other render resources here
    D3D11_TILED_EMULATION_PARAMETERS EmulationParams;
    EmulationParams.DefaultPhysicalTileFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
    EmulationParams.MaxPhysicalTileCount = 1000;
    D3D11CreateTiledResourceDevice( pd3dDevice, pd3dImmediateContext, &EmulationParams, &g_pd3dDeviceEx );

    g_pd3dDeviceEx->CreateTilePool( &g_pTilePool );

    g_pTitleResidencyManager = new TitleResidencyManager( pd3dDevice, pd3dImmediateContext, 1, EmulationParams.MaxPhysicalTileCount, g_pTilePool );

    ResidencySampleRender::Initialize( pd3dDevice );

    g_PageDebugRender.Initialize( pd3dDevice );

    CreateSceneGeometry( pd3dDevice );

    // Setup the camera's view parameters
    XMMATRIX matProjection = XMMatrixPerspectiveFovLH( XM_PIDIV4, (FLOAT)pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height, 0.001f, 100.0f );
    XMStoreFloat4x4A( &g_matProjection, matProjection );

    UpdateViewMatrix();

    g_pTitleResidencyManager->StartThreads();

    return S_OK;
}
Beispiel #21
0
void ObjMeshInfo::loadMesh(ID3D11Device* pd3dDevice)
{
	if (!fromFile)
	{
		specialLoad(pd3dDevice);
		return;
	}

	std::wifstream          fileStream;
	std::wstring            line;
	std::vector <XMFLOAT3> vectorVertices(0);
	std::vector <XMFLOAT3> vectorNormals(0);
	std::vector <XMFLOAT2> vectorUVs(0);
	std::vector <Index>    vectorIndices(0);
	std::vector <Material> vectorTextureFiles(0);

	fileStream.open(file);
	bool isOpen = fileStream.is_open();		//debugging only.

	// convert LPCTSTR to WCHAR
	WCHAR wfile[200];
	wcscpy(wfile, file);

	// get the folder so we can prepend it to filenames later
	WCHAR folder[200];
	getFolder(folder, wfile);


	bool newMaterial = false;
	WCHAR materialName[200];

	// now we can start to read the obj file!
	while (std::getline(fileStream, line))
	{
		line = TrimStart(line);

		// materials
		if (line.compare(0, 7, L"usemtl ") == 0)
		{
			WCHAR first[20];
			// I'm actually treating a 'material' as a submesh. not sure if this is correct

			WCHAR oldStyleStr[200];
			wcscpy(oldStyleStr, line.c_str());
			swscanf(oldStyleStr, L"%7s%s", first, materialName);

			// we want the next index to have the newMaterial flag
			newMaterial = true;

			continue;
		}

		//******************************************************************//
		// If true, we have found a vertex.  Read it in as a 2 character	//
		// string, followed by 3 decimal numbers.	Suprisingly the C++		//
		// string has no split() method.   I am using really old stuff,		//
		// fscanf.  There  must be a better way, use regular expressions?	//
		//******************************************************************//
		if (line.compare(0, 2, L"v ") == 0)  //"v space"
		{
			WCHAR first[10];
			float x, y, z;

			WCHAR oldStyleStr[200];
			wcscpy(oldStyleStr, line.c_str());
			swscanf(oldStyleStr, L"%2s%f%f%f", first, &x, &y, &z);

			XMFLOAT3 v = XMFLOAT3(x, y, z);
			vectorVertices.push_back(v);
			continue;
		}

		// normals
		if (line.compare(0, 3, L"vn ") == 0)  //"vn space"
		{
			WCHAR first[10];
			float x, y, z;

			WCHAR oldStyleStr[200];
			wcscpy(oldStyleStr, line.c_str());
			swscanf(oldStyleStr, L"%3s%f%f%f", first, &x, &y, &z);

			XMFLOAT3 v = XMFLOAT3(x, y, z);
			vectorNormals.push_back(v);
			continue;
		}

		// texture coordinates
		if (line.compare(0, 3, L"vt ") == 0)  //"vt space"
		{
			WCHAR first[10];
			float u, v;

			WCHAR oldStyleStr[200];
			wcscpy(oldStyleStr, line.c_str());
			swscanf(oldStyleStr, L"%3s%f%f", first, &u, &v);

			XMFLOAT2 vert = XMFLOAT2(u, v); 
			vectorUVs.push_back(vert);
			continue;
		}

		//******************************************************************//
		// If true, we have found a face.   Read it in as a 2 character		//
		// string, followed by 3 decimal numbers.	Suprisingly the C++		//
		// string has no split() method.   I am using really old stuff,		//
		// fscanf.  There must be a better way, use regular expressions?	//
		//																	//
		// It assumes the line is in the format								//
		// f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3 ...							//
		//******************************************************************// 
		if (line.compare(0, 2, L"f ") == 0)  //"f space"
		{
			WCHAR first[10];
			WCHAR slash1[10];
			WCHAR slash2[10];
			WCHAR slash3[10];
			WCHAR slash4[10];
			WCHAR slash5[10];
			WCHAR slash6[10];

			UINT v1, vt1, vn1, v2, vt2, vn2, v3, vt3, vn3;

			WCHAR oldStyleStr[200];
			wcscpy(oldStyleStr, line.c_str());
			swscanf(oldStyleStr, L"%2s%d%1s%d%1s%d%d%1s%d%1s%d%d%1s%d%1s%d", first,
				&v1, slash1, &vt1, slash2, &vn1,
				&v2, slash3, &vt2, slash4, &vn2,
				&v3, slash5, &vt3, slash6, &vn3);

			Index input;

			input.v = v1 - 1;
			input.vt = vt1 - 1;
			input.vn = vn1 - 1;

			if (newMaterial)
			{
				input.newMaterial = true;
				wcscpy(input.materialName, materialName);
				newMaterial = false;
			}

			vectorIndices.push_back(input);
			input.newMaterial = false;

			input.v = v2 - 1;
			input.vt = vt2 - 1;
			input.vn = vn2 - 1;
			vectorIndices.push_back(input);

			input.v = v3 - 1;
			input.vt = vt3 - 1;
			input.vn = vn3 - 1;
			vectorIndices.push_back(input);

			continue;
		}

		// get mtl file name
		if (line.compare(0, 7, L"mtllib ") == 0)
		{
			WCHAR first[10], mtlFileName[200];

			WCHAR oldStyleStr[200];
			wcscpy(oldStyleStr, line.c_str());
			swscanf(oldStyleStr, L"%7s%s", first, &mtlFileName);

			// read the mtl file
			// we need to prepend the folder name and stuff to the mtl file name
			WCHAR fullMtlFilePath[200];
			wcscpy(fullMtlFilePath, folder);
			wcsncat(fullMtlFilePath, mtlFileName, 200);

			readMtlFile(&vectorTextureFiles, fullMtlFilePath, folder);

			continue;
		}
	}


	//******************************************************************//
	// SIMPLIFICATION													//
	//******************************************************************//

	// so the problem with obj files is that the indices are stored as v/vt/vn
	// whereas directx can only handle indices of ...vertices (as far as I'm aware)
	// so what we need to do is find the indices that are completely unique (completely original combination of v/vt/vn)
	// and make them vertices, referencing them with 1 number instead of 3

	std::vector <SimpleVertex>	simplifiedVertices(0);
	std::vector <Index>			uniqueIndices(0);
	std::vector <MeshMaterial>		vectorSubsets(0);


	USHORT uniqueIndexCount = 0;
	USHORT subsetIndexCount = 0;
	USHORT totalIndexCount = 0;

	// for each index
	for (int i = 0; i < vectorIndices.size(); i++)
	{
		Index idx = vectorIndices[i];

		// if idx is the first index of a new material
		if (idx.newMaterial)
		{
			// if this is not the first subset, we need to set the index count of the previous subset
			if (vectorSubsets.size() > 0)
			{
				vectorSubsets.back().subset.ic = subsetIndexCount;
				subsetIndexCount = 0;
			}
		
			// create a new subset
			// this means we're creating a new subset even if we've already created one for the same material earlier on
			// (and if the obj file doesn't start with a material this will go horribly wrong)
			MeshMaterial meshMaterial;
			meshMaterial.subset.is = totalIndexCount;
			meshMaterial.subset.vs = simplifiedVertices.size();
			// also, we need to wipe the uniqueIndices vector, because we don't want indices from different subsets referencing the same vertices
			uniqueIndices.clear();
			uniqueIndexCount = 0;

			// find the material properties
			// which at the moment consists of just the texture
			for (int i = 0; i < vectorTextureFiles.size(); i++)
			{
				// if the material name matches
				if (wcscmp(idx.materialName, vectorTextureFiles[i].materialName) == 0)
				{
					Material * material = &vectorTextureFiles[i];
					if (material->hasTexture)
					{
						wcscpy(meshMaterial.textureFilePath, material->textureFilePath);
						meshMaterial.hasTexture = true;
					}

					//meshMaterial.subset.color = vectorTextureFiles[i].color;
				}
			}

			vectorSubsets.push_back(meshMaterial);
		}


		std::vector <Index> matchingV(0);

		// of uniqueIndices, find matching v
		for (size_t i = 0; i < uniqueIndices.size(); i++)
		{
			Index vert = uniqueIndices[i];
			if (idx.v == vert.v)
			{
				// add to matchingV
				matchingV.push_back(vert);
			}
		}

		std::vector <Index> matchingVn(0);
		// of the ones we found, find matching vn
		for (size_t i = 0; i < matchingV.size(); i++)
		{
			Index vert = matchingV[i];
			if (idx.vn == vert.vn)
			{
				// add to matchingVn
				matchingVn.push_back(vert);
			}
		}

		std::vector <Index> matchingVt(0);
		// of the ones we found, find matching vt
		for (size_t i = 0; i < matchingVn.size(); i++)
		{
			Index vert = matchingVn[i];
			if (idx.vt == vert.vt)
			{
				// add to matchingVn
				matchingVt.push_back(vert);
			}
		}

		USHORT thisIndex;

		// if matchingVt is empty then this is unique
		if (matchingVt.size() == 0)
		{
			// create a uniqueIndex
			Index uniqueIndex = idx;
			uniqueIndex.vertex = uniqueIndexCount;
			uniqueIndices.push_back(uniqueIndex);

			// this is where we also create the vertex
			SimpleVertex newVertex;
			// we have to get the data from the vectors
			newVertex.Pos = vectorVertices[idx.v];
			newVertex.TexUV = vectorUVs[idx.vt];
			newVertex.VecNormal = vectorNormals[idx.vn];
			
			simplifiedVertices.push_back(newVertex);

			// also do this
			thisIndex = uniqueIndexCount;
			uniqueIndexCount++;
		}
		else
		{
			// otherwise there should be one left, meaning we got a complete match
			// now we can reference that vertex instead
			thisIndex = matchingVt[0].vertex;
		}
		
		vectorIndices[i].vertex = thisIndex;
		subsetIndexCount++;
		totalIndexCount++;
	}

	// we need to set the index count of the final subset here
	// we're not checking if vectorSubsets.size() is zero because that should never happen!
	vectorSubsets.back().subset.ic = subsetIndexCount;

	//******************************************************************//
	// SUBSETS															//
	//******************************************************************//

	objMesh.numSs = vectorSubsets.size();
	objMesh.subsets = new ObjMeshSubset[objMesh.numSs];
	for (int i = 0; i < objMesh.numSs; i++)
	{
		objMesh.subsets[i] = vectorSubsets[i].subset;

		// also do the textures while we're here
		ObjMeshSubset * subset = &objMesh.subsets[i];
		subset->hastxtrz = vectorSubsets[i].hasTexture;

		if (subset->hastxtrz)
		{
			// create the texture resource
			D3DX11CreateShaderResourceViewFromFile(pd3dDevice,
				vectorSubsets[i].textureFilePath,
				NULL, NULL,
				&subset->txtr,		// This is returned.
				NULL);
			DXUT_SetDebugName(subset->txtr, "MESH_TEXTURE");
		}
	}

	//******************************************************************//
	// VERTICES															//
	//******************************************************************//

	objMesh.numVertices = simplifiedVertices.size();
	objMesh.vertices = new SimpleVertex[objMesh.numVertices];
	for (int i = 0; i < objMesh.numVertices; i++)
		objMesh.vertices[i] = simplifiedVertices[i];


	//******************************************************************//
	// INDICES															//
	//******************************************************************//

	objMesh.numIndices = vectorIndices.size();
	objMesh.indexes = new USHORT[objMesh.numIndices];
	for (int i = 0; i < objMesh.numIndices; i++)
		objMesh.indexes[i] = vectorIndices[i].vertex;


	//******************************************************************//
	// BUFFERS															//
	//******************************************************************//

	// Create the vertex buffer
	D3D11_BUFFER_DESC bd;
	ZeroMemory(&bd, sizeof(bd));
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof(SimpleVertex) * objMesh.numVertices;
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = 0;
	D3D11_SUBRESOURCE_DATA InitData;
	ZeroMemory(&InitData, sizeof(InitData));
	InitData.pSysMem = objMesh.vertices;

	pd3dDevice->CreateBuffer(&bd, &InitData, &objMesh.vb);
	DXUT_SetDebugName(objMesh.vb, "VERTEX_BUFFER");

	// create the index buffer
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof(USHORT) * objMesh.numIndices;

	bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	bd.CPUAccessFlags = 0;
	InitData.pSysMem = objMesh.indexes;

	pd3dDevice->CreateBuffer(&bd, &InitData, &objMesh.ib);
	DXUT_SetDebugName(objMesh.ib, "INDEX_BUFFER");
}
//--------------------------------------------------------------------------------------
// Create any D3D11 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
                                      void* pUserContext )
{
    HRESULT hr;

    ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext();
    V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) );
    V_RETURN( g_D3DSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) );
    g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 );

   // D3DXVECTOR3 vCenter( 0.25767413f, -28.503521f, 111.00689f );
    FLOAT fObjectRadius = 378.15607f;
	lightpos = D3DXVECTOR3(300,300,-200);
	//test = new testing();
	hr = test.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext);
	hr = tessplane.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext);
	hr = tesscube.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext,80,D3DXVECTOR3(300,50,-200));//D3DXVECTOR3(300,50,-200
	hr = lightsphere.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext,10,lightpos);
	hr = fuse.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext);
	hr = board1.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext,D3DXVECTOR3(300,-300,-1000));
	hr = deboard.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext,D3DXVECTOR3(-300,-300,-1000));
	hr = geo_alien.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext);
	hr = FirePart.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext,80,0); //0 = fire
	hr = sky.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext,D3DXVECTOR3(0,0,0));
	hr = buildings.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext);
	hr = MissilePart.setup(pd3dDevice,pBackBufferSurfaceDesc,pUserContext,20,1);
    g_LightControl.SetRadius( 2000 );



	
    // Setup the camera's view parameters
    D3DXVECTOR3 vecEye( 0.0f, 50.0f, -1000.0f );
    D3DXVECTOR3 vecAt ( 0.0f, 0.0f, -0.0f );

	g_Camera.SetRotateButtons(true,false,false);
    g_Camera.SetViewParams( &vecEye, &vecAt );
	g_Camera.SetEnablePositionMovement( true );
	g_Camera.SetScalers( 0.005f, 500.0f );

	D3D11_DEPTH_STENCIL_DESC descDS;
	ZeroMemory(&descDS, sizeof(descDS));
	descDS.DepthEnable = false;
	descDS.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;	
	descDS.DepthFunc = D3D11_COMPARISON_LESS;	
	

	descDS.StencilEnable = FALSE;
	hr = pd3dDevice->CreateDepthStencilState( &descDS, &g_DepthState);

	//setup stuff for post process


	ID3DBlob* pVertexShaderBuffer = NULL;
    V_RETURN( CompileShaderFromFile( L"PP1.hlsl", "VS", "vs_4_0", &pVertexShaderBuffer ) );

    ID3DBlob* pPixelShaderBuffer = NULL;
    V_RETURN( CompileShaderFromFile( L"PP1.hlsl", "PS", "ps_4_0", &pPixelShaderBuffer ) );

	V_RETURN( pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(),
                                              pVertexShaderBuffer->GetBufferSize(), NULL, &VSPPFirstPass ) );
    DXUT_SetDebugName( VSPPFirstPass, "VSPost1" );
    V_RETURN( pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(),
                                             pPixelShaderBuffer->GetBufferSize(), NULL, &PSPPFirstPass ) );
    DXUT_SetDebugName( PSPPFirstPass, "PSPost1" );

	pVertexShaderBuffer = NULL;
    V_RETURN( CompileShaderFromFile( L"Gaussblur.hlsl", "VS", "vs_4_0", &pVertexShaderBuffer ) );

    pPixelShaderBuffer = NULL;
    V_RETURN( CompileShaderFromFile( L"Gaussblur.hlsl", "PS", "ps_4_0", &pPixelShaderBuffer ) );

	V_RETURN( pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(),
                                              pVertexShaderBuffer->GetBufferSize(), NULL, &VSPPBlur ) );
    DXUT_SetDebugName( VSPPBlur, "VSBlur" );
    V_RETURN( pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(),
                                             pPixelShaderBuffer->GetBufferSize(), NULL, &PSPPBlur ) );
    DXUT_SetDebugName( PSPPBlur, "PSBlur" );

	pVertexShaderBuffer = NULL;
    V_RETURN( CompileShaderFromFile( L"bloom_combine.hlsl", "VS", "vs_4_0", &pVertexShaderBuffer ) );

    pPixelShaderBuffer = NULL;
    V_RETURN( CompileShaderFromFile( L"bloom_combine.hlsl", "PS", "ps_4_0", &pPixelShaderBuffer ) );

	V_RETURN( pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(),
                                              pVertexShaderBuffer->GetBufferSize(), NULL, &VSPPComb ) );
    DXUT_SetDebugName( VSPPComb, "VSComb" );
    V_RETURN( pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(),
                                             pPixelShaderBuffer->GetBufferSize(), NULL, &PSPPComb ) );
    DXUT_SetDebugName( PSPPComb, "PSComb" );





	
	D3D11_BUFFER_DESC Desc;
    Desc.Usage = D3D11_USAGE_DYNAMIC;
    Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    Desc.MiscFlags = 0;

    Desc.ByteWidth = sizeof( blur_cbuffer );
    V_RETURN( pd3dDevice->CreateBuffer( &Desc, NULL, &blur_cb_buffer ) );
    DXUT_SetDebugName( blur_cb_buffer, "blur_cb" );


    //g_Camera.SetRadius( fObjectRadius * 3.0f, fObjectRadius * 0.5f, fObjectRadius * 10.0f );
    return S_OK;
}
Beispiel #23
0
//--------------------------------------------------------------------------------------
// FillGrid_WithNormals_Indexed
// Creates a regular grid of indexed triangles, including normals.
//
// Parameters:
//
// IN
// pd3dDevice:               The D3D device
// dwWidth, dwLength:        Number of grid vertices in X and Z direction
// fGridSizeX, fGridSizeZ:   Grid extents in local space units
//
// OUT
// lplpVB:                   A pointer to the vertex buffer containing grid vertices
// lplpIB:                   A pointer to the index buffer containing grid indices
//--------------------------------------------------------------------------------------
void FillGrid_WithNormals_Indexed( ID3D11Device* pd3dDevice, DWORD dwWidth, DWORD dwLength, 
                                   float fGridSizeX, float fGridSizeZ, 
                                   ID3D11Buffer** lplpVB, ID3D11Buffer** lplpIB )
{
    HRESULT      hr;
    DWORD        nNumVertex = ( dwWidth + 1 ) * ( dwLength + 1 );
    DWORD        nNumIndex = 3 * 2 * dwWidth * dwLength;
    float        fStepX = fGridSizeX / dwWidth;
    float        fStepZ = fGridSizeZ / dwLength;
    
    // Allocate memory for buffer of vertices in system memory
    EXTENDEDVERTEX*    pVertexBuffer = new EXTENDEDVERTEX[nNumVertex];
    EXTENDEDVERTEX*    pVertex = &pVertexBuffer[0];

    // Fill vertex buffer
    for ( DWORD i=0; i<=dwLength; ++i )
    {
        for ( DWORD j=0; j<=dwWidth; ++j )
        {
            pVertex->x = -fGridSizeX/2.0f + j*fStepX;
            pVertex->y = 0.0f;
            pVertex->z = fGridSizeZ/2.0f - i*fStepZ;
            pVertex->nx = 0.0f;
            pVertex->ny = 0.0f;
            pVertex->nz = 0.0f;
            pVertex->u = 0.0f + ( (float)j / dwWidth  );
            pVertex->v = 0.0f + ( (float)i / dwLength );
            pVertex++;
        }
    }

    // Allocate memory for buffer of indices in system memory
    WORD*    pIndexBuffer = new WORD [nNumIndex];
    WORD*    pIndex = &pIndexBuffer[0];

    // Fill index buffer
    for ( DWORD i=0; i<dwLength; ++i )
    {
        for ( DWORD j=0; j<dwWidth; ++j )
        {
            *pIndex++ = (WORD)(   i     * ( dwWidth+1 ) + j );
            *pIndex++ = (WORD)(   i     * ( dwWidth+1 ) + j + 1 );
            *pIndex++ = (WORD)( ( i+1 ) * ( dwWidth+1 ) + j );

            *pIndex++ = (WORD)( ( i+1 ) * (dwWidth+1) + j );
            *pIndex++ = (WORD)(   i     * (dwWidth+1) + j + 1 );
            *pIndex++ = (WORD)( ( i+1 ) * (dwWidth+1) + j + 1 );
        }
    }

    // Set initial data info
    D3D11_SUBRESOURCE_DATA InitData;
    InitData.pSysMem = pIndexBuffer;

    // Fill DX11 index buffer description
    D3D11_BUFFER_DESC    bd;
    bd.Usage =           D3D11_USAGE_DEFAULT;
    bd.ByteWidth =       sizeof( WORD ) * nNumIndex;
    bd.BindFlags =       D3D11_BIND_INDEX_BUFFER;
    bd.CPUAccessFlags =  0;
    bd.MiscFlags =       0;
    
    // Create DX11 index buffer specifying initial data
    hr = pd3dDevice->CreateBuffer( &bd, &InitData, lplpIB );
    if( FAILED( hr ) )
    {
        OutputDebugString( L"FillGrid_WithNormals_Indexed: Failed to create index buffer.\n" );
        return;
    }
    DXUT_SetDebugName( *lplpIB, "FillGrid IB Nrmls" );

    // Write normals into vertex buffer
    pVertex = &pVertexBuffer[0];

    // Loop through all indices
    for ( DWORD i=0; i<nNumIndex/3; ++i )
    {
        WORD i1 = pIndexBuffer[3*i + 0];
        WORD i2 = pIndexBuffer[3*i + 1];
        WORD i3 = pIndexBuffer[3*i + 2];
        D3DXVECTOR3 Normal = CalculateTriangleNormal( (D3DXVECTOR3 *)&pVertexBuffer[i1].x, 
                                                      (D3DXVECTOR3 *)&pVertexBuffer[i2].x, 
                                                      (D3DXVECTOR3 *)&pVertexBuffer[i3].x );

        // Add normal to each vertex for this triangle
        *( (D3DXVECTOR3 *)&pVertexBuffer[i1].nx ) += Normal;
        *( (D3DXVECTOR3 *)&pVertexBuffer[i2].nx ) += Normal;
        *( (D3DXVECTOR3 *)&pVertexBuffer[i3].nx ) += Normal;
    }

    // Final normalization pass
    for ( DWORD i=0; i<nNumVertex; ++i )
    {
        D3DXVec3Normalize( (D3DXVECTOR3 *)&pVertexBuffer[i].nx, (D3DXVECTOR3 *)&pVertexBuffer[i].nx );
    }


    // Set initial data info
    InitData.pSysMem = pVertexBuffer;

    // Fill DX11 vertex buffer description
    bd.Usage =            D3D11_USAGE_DEFAULT;
    bd.ByteWidth =        sizeof( EXTENDEDVERTEX ) * nNumVertex;
    bd.BindFlags =        D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags =   0;
    bd.MiscFlags =        0;

    // Create DX11 vertex buffer specifying initial data
    hr = pd3dDevice->CreateBuffer( &bd, &InitData, lplpVB );
    if( FAILED( hr ) )
    {
        OutputDebugString( L"FillGrid_WithNormals_Indexed: Failed to create vertex buffer.\n" );
        return;
    }
    DXUT_SetDebugName( *lplpVB, "FillGrid VB Nrmls Idx" );

    // Release host memory index buffer
    delete [] pIndexBuffer;

    // Release host memory vertex buffer
    delete [] pVertexBuffer;

}
//--------------------------------------------------------------------------------------
// render callback
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, 
                                  ID3D11DeviceContext* pd3dImmediateContext, 
                                  double fTime,
                                  float fElapsedTime, void* pUserContext )
{
    static int s_iCounter = 0;

    // If the settings dialog is being shown, then render it instead of rendering the app's scene
    if( g_D3DSettingsDlg.IsActive() )
    {
        g_D3DSettingsDlg.OnRender( fElapsedTime );
        return;
    }

    if( g_pScenePS == NULL && s_iCounter == 0 )
    {
        s_iCounter = 4;
    }

    if( s_iCounter > 0 )
        s_iCounter --;

    if( s_iCounter == 1 && g_pScenePS == NULL )
    {
        HRESULT hr = S_OK;

        // Create the shaders
        ID3DBlob* pBlob = NULL;

        // VS
        hr = CompileShaderFromFile( L"ContactHardeningShadows11.hlsl", "VS_RenderScene", "vs_5_0", &pBlob ); 
        hr = pd3dDevice->CreateVertexShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &g_pSceneVS );
        DXUT_SetDebugName( g_pSceneVS, "VS_RenderScene" );
        // Define our scene vertex data layout
        const D3D11_INPUT_ELEMENT_DESC SceneLayout[] =
        {
            { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
            { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
            { "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        };
        hr = pd3dDevice->CreateInputLayout( SceneLayout, ARRAYSIZE( SceneLayout ), pBlob->GetBufferPointer(),
                                                    pBlob->GetBufferSize(), &g_pSceneVertexLayout );
        SAFE_RELEASE( pBlob );
        DXUT_SetDebugName( g_pSceneVertexLayout, "SceneLayout" );

        hr = CompileShaderFromFile( L"ContactHardeningShadows11.hlsl", "VS_RenderSceneSM", "vs_5_0", &pBlob ); 
        hr = pd3dDevice->CreateVertexShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &g_pSM_VS );
        SAFE_RELEASE( pBlob );
        DXUT_SetDebugName( g_pSM_VS, "VS_RenderSceneSM" );

        // PS
        hr = CompileShaderFromFile( L"ContactHardeningShadows11.hlsl", "PS_RenderScene", "ps_5_0", &pBlob ); 
        hr = pd3dDevice->CreatePixelShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &g_pScenePS );
        SAFE_RELEASE( pBlob );
        DXUT_SetDebugName( g_pScenePS, "PS_RenderScene" );

        s_iCounter = 0;
    }
    else if( g_pScenePS != NULL )
    {
        ID3D11RenderTargetView*      pRTV[2] = { NULL,NULL };
        ID3D11ShaderResourceView*    pSRV[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

        // Array of our samplers
        ID3D11SamplerState* ppSamplerStates[3] = { g_pSamplePoint, g_pSampleLinear, g_pSamplePointCmp };

        pd3dImmediateContext->PSSetSamplers( 0, 3, ppSamplerStates );
                
            // Store off original render target, this is the back buffer of the swap chain
        ID3D11RenderTargetView* pOrigRTV = DXUTGetD3D11RenderTargetView();
        ID3D11DepthStencilView* pOrigDSV = DXUTGetD3D11DepthStencilView();
            
        // Clear the render target
        float ClearColor[4] = { 0.0f, 0.25f, 0.25f, 0.55f };
        pd3dImmediateContext->ClearRenderTargetView( DXUTGetD3D11RenderTargetView(), 
                                                     ClearColor );
        pd3dImmediateContext->ClearDepthStencilView( DXUTGetD3D11DepthStencilView(), 
                                                     D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 
                                                     1.0, 0 );

            // Get the projection & view matrix from the camera class
        D3DXMATRIXA16 mWorld;
        D3DXMATRIXA16 mView;
        D3DXMATRIXA16 mProj;
        D3DXMATRIXA16 mViewProjLight;
        D3DXMATRIXA16 mWorldViewProjection;
        D3DXVECTOR3   vLightDir;

        // disable color writes
        pd3dImmediateContext->OMSetBlendState(g_pBlendStateColorWritesOff, 0, 0xffffffff);

        RenderShadowMap( pd3dDevice, pd3dImmediateContext, mViewProjLight, vLightDir );

        // enable color writes
        pd3dImmediateContext->OMSetBlendState(g_pBlendStateNoBlend, 0, 0xffffffff);

        mView  = *g_Camera.GetViewMatrix();
        mProj  = *g_Camera.GetProjMatrix();
        mWorldViewProjection = mView * mProj;

        // Setup the constant buffer for the scene vertex shader
        D3D11_MAPPED_SUBRESOURCE MappedResource;
        pd3dImmediateContext->Map( g_pcbConstants, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource );
        CB_CONSTANTS* pConstants = ( CB_CONSTANTS* )MappedResource.pData;
        D3DXMatrixTranspose( &pConstants->f4x4WorldViewProjection, &mWorldViewProjection );
        D3DXMatrixTranspose( &pConstants->f4x4WorldViewProjLight,  &mViewProjLight );
        pConstants->vShadowMapDimensions =    D3DXVECTOR4(g_fShadowMapWidth, g_fShadowMapHeight, 
                                                          1.0f/g_fShadowMapWidth, 
                                                          1.0f/g_fShadowMapHeight);
        pConstants->vLightDir            =    D3DXVECTOR4( vLightDir.x, vLightDir.y,
                                                           vLightDir.z, 0.0f );
        pConstants->fSunWidth            =    g_fSunWidth;
        pd3dImmediateContext->Unmap( g_pcbConstants, 0 );
        pd3dImmediateContext->VSSetConstantBuffers( g_iCONSTANTSCBBind, 1, &g_pcbConstants );
        pd3dImmediateContext->PSSetConstantBuffers( g_iCONSTANTSCBBind, 1, &g_pcbConstants );

        // Set the shaders
        pd3dImmediateContext->VSSetShader( g_pSceneVS, NULL, 0 );
        pd3dImmediateContext->PSSetShader( g_pScenePS, NULL, 0 );

        // Set the vertex buffer format
        pd3dImmediateContext->IASetInputLayout( g_pSceneVertexLayout );
        
        // Rebind to original back buffer and depth buffer
        pRTV[0] = pOrigRTV;
        pd3dImmediateContext->OMSetRenderTargets(1, pRTV, pOrigDSV );

        // set the shadow map
        pd3dImmediateContext->PSSetShaderResources( 1, 1, &g_pDepthTextureSRV );

        // Render the scene
        g_SceneMesh.Render( pd3dImmediateContext, 0 );
        g_Poles.Render( pd3dImmediateContext, 0 );

        // restore resources
        pd3dImmediateContext->PSSetShaderResources( 0, 8, pSRV );
    }

    // Render GUI
    DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );
    if( g_bGuiVisible )
    {
        g_HUD.OnRender( fElapsedTime );
        g_SampleUI.OnRender( fElapsedTime );
    }
    RenderText();
    DXUT_EndPerfEvent();
}