Example #1
0
void TestTriangleStripsDX::Update()
{
	if (processInput)
	{
		float rotAmount = 0.0f;
		XMMATRIX rotMatrix = XMMatrixIdentity();
		if (input.right || input.left)
		{
			if (input.right)
				rotAmount = rotDelta;
			if (input.left)
				rotAmount = -rotDelta;
			rotMatrix = XMMatrixRotationAxis(XMLoadFloat4(&up), XMConvertToRadians(rotAmount));
		}
		else if (input.up || input.down)
		{
			if (input.up)
				rotAmount = rotDelta;
			if (input.down)
				rotAmount = -rotDelta;
			rotMatrix = XMMatrixRotationAxis(XMLoadFloat4(&right), XMConvertToRadians(rotAmount));
		}

		XMStoreFloat4(&eye, XMVector3Transform(XMLoadFloat4(&eye), rotMatrix));
		XMStoreFloat4(&right, XMVector3Normalize(XMVector3Cross(XMLoadFloat4(&up), (XMLoadFloat4(&center) - XMLoadFloat4(&eye)))));

		XMMATRIX viewMatrix = XMMatrixLookAtRH(XMLoadFloat4(&eye), XMLoadFloat4(&center), XMLoadFloat4(&up));
		mDeviceContext->UpdateSubresource(viewMatrixBuffer, 0, NULL, &viewMatrix, 0, 0);
	}
}
Example #2
0
void Camera::updateView() {
    XMVECTOR pos = XMLoadFloat3(&_position);
    XMVECTOR tar = XMLoadFloat3(&_target);
    XMVECTOR up  = XMLoadFloat3(&_up);

    XMMATRIX mat = XMMatrixLookAtRH(pos, tar, up);
    XMStoreFloat4x4(&_view, mat);
}
Example #3
0
void Engine::PerspCamera::position(void) const
{
	*_frusSpherePosition = *_vforward * _frusSphereDistance;

	*_viewMatrix = XMMatrixLookAtRH(*_pcamera, *_pcamera + * _vforward, *_vup);
	*_VPMatrix = *_viewMatrix * *_projectionMatrix;
	*_IVPMatrix = XMMatrixInverse(NULL, *_VPMatrix);
}
Example #4
0
void SceneInt::InitialiseBuffers()
{
    XMVECTOR eye = XMVectorSet(-10.0f, 0.7f, -8.0f, 0.0f);
    XMVECTOR at = XMVectorSet(0.0f, 8.0f, 0.0f, 0.0f);
    XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

	auto matrix = XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up));
	XMStoreFloat4x4(&_constantBufferData.view, matrix);
}
void GraphicCameraEntity::UpdateView2D(std::shared_ptr<CameraEntity> obj)
{
	float widthHalf = this->Width / 2.f;
	float heightHalf = this->Height / 2.f;
	XMVECTOR vEye = XMVectorSet(widthHalf, heightHalf, 0.0, 0.0);
	XMVECTOR vTM = XMVectorSet(0.0, 0.0, 1.0, 0.0);
	XMVECTOR vUp = XMVectorSet(0.0, -1.0, 0.0, 0.0);

	vTM += vEye;

	XMStoreFloat4x4(&this->View2D, XMMatrixLookAtRH(vEye, vTM, vUp));
}
void Camera::Get3DViewProjMatrices(XMFLOAT4X4 *view, XMFLOAT4X4 *proj, float fovInDegrees, float screenWidth, float screenHeight)
{
	
	float aspectRatio = (float)screenWidth / (float)screenHeight;
	float fovAngleY = fovInDegrees * XM_PI / 180.0f;

	if (aspectRatio < 1.0f)
	{
		fovAngleY /= aspectRatio;
	}

	XMStoreFloat4x4(view, XMMatrixTranspose(XMMatrixLookAtRH(mEye, mAt, mUp)));
	XMStoreFloat4x4(proj, XMMatrixTranspose(XMMatrixPerspectiveFovRH(fovAngleY, aspectRatio, 0.01f, 125.0f)));
}
Example #7
0
void GuardianSystemDemo::Render()
{
    // Get current eye pose for rendering
    double eyePoseTime = 0;
    ovrPosef eyePose[ovrEye_Count] = {};
    ovr_GetEyePoses(mSession, mFrameIndex, ovrTrue, mHmdToEyeOffset, eyePose, &eyePoseTime);

    // Render each eye
    for (int i = 0; i < ovrEye_Count; ++i) {
        int renderTargetIndex = 0;
        ovr_GetTextureSwapChainCurrentIndex(mSession, mTextureChain[i], &renderTargetIndex);
        ID3D11RenderTargetView* renderTargetView = mEyeRenderTargets[i][renderTargetIndex];
        ID3D11DepthStencilView* depthTargetView = mEyeDepthTarget[i];

        // Clear and set render/depth target and viewport
        DIRECTX.SetAndClearRenderTarget(renderTargetView, depthTargetView, 0.2f, 0.2f, 0.2f, 1.0f);
        DIRECTX.SetViewport((float)mEyeRenderViewport[i].Pos.x, (float)mEyeRenderViewport[i].Pos.y, 
            (float)mEyeRenderViewport[i].Size.w, (float)mEyeRenderViewport[i].Size.h);

        // Eye
        XMVECTOR eyeRot = XMVectorSet(eyePose[i].Orientation.x, eyePose[i].Orientation.y, 
            eyePose[i].Orientation.z, eyePose[i].Orientation.w);
        XMVECTOR eyePos = XMVectorSet(eyePose[i].Position.x, eyePose[i].Position.y, eyePose[i].Position.z, 0);
        XMVECTOR eyeForward = XMVector3Rotate(XMVectorSet(0, 0, -1, 0), eyeRot);

        // Matrices
        XMMATRIX viewMat = XMMatrixLookAtRH(eyePos, XMVectorAdd(eyePos, eyeForward), 
            XMVector3Rotate(XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f), eyeRot));
        ovrMatrix4f proj = ovrMatrix4f_Projection(mEyeRenderLayer.Fov[i], 0.001f, 1000.0f, ovrProjection_None);
        XMMATRIX projMat = XMMatrixTranspose(XMMATRIX(&proj.M[0][0]));
        XMMATRIX viewProjMat = XMMatrixMultiply(viewMat, projMat);

        // Render and commit to swap chain
        mDynamicScene.Render(&viewProjMat, 1.0f, 1.0f, 1.0f, 1.0f, true);
        ovr_CommitTextureSwapChain(mSession, mTextureChain[i]);

        // Update eye layer
        mEyeRenderLayer.ColorTexture[i] = mTextureChain[i];
        mEyeRenderLayer.RenderPose[i] = eyePose[i];
        mEyeRenderLayer.SensorSampleTime = eyePoseTime;
    }

    // Submit frames
    ovrLayerHeader* layers = &mEyeRenderLayer.Header;
    ovrResult result = ovr_SubmitFrame(mSession, mFrameIndex++, nullptr, &layers, 1);
    if (!OVR_SUCCESS(result)) {
        printf("ovr_SubmitFrame failed"); exit(-1);
    }
}
void GraphicCameraEntity::UpdateView(std::shared_ptr<CameraEntity> obj)
{
	const XMFLOAT4& f4Eye = this->Eye;
	XMVECTOR vEye = XMVectorSet(f4Eye.x, f4Eye.y, f4Eye.z, f4Eye.w);
	const XMFLOAT4& f4Up = this->Up;
	XMVECTOR vUp = XMVectorSet(f4Up.x, f4Up.y, f4Up.z, f4Up.w);
	const XMFLOAT4& f4TM = this->TargetMagnitude;
	XMVECTOR vTM = XMVectorSet(f4TM.x, f4TM.y, f4TM.z, f4TM.w);

	XMMATRIX RotationMatrix = XMMatrixRotationRollPitchYaw(this->GetPitch(), this->GetYaw(), this->GetRoll());

	vTM = XMVector3TransformCoord(vTM, RotationMatrix);
	vUp = XMVector3TransformCoord(vUp, RotationMatrix);

	vTM += vEye;

	XMStoreFloat4x4(&this->View, XMMatrixLookAtRH(vEye, vTM, vUp));
}
Example #9
0
void XM_CALLCONV Camera::Update( FXMVECTOR _pos, FXMVECTOR target ) {
	pos = _pos;
	view = XMMatrixLookAtRH( pos, target, up );
	viewProj = view*proj;
}
void Camera::GetOrthoProjMatrices(XMFLOAT4X4 *view, XMFLOAT4X4 *proj, float width, float height)
{
	XMStoreFloat4x4(view, XMMatrixTranspose(XMMatrixLookAtRH(mEye, mAt, mUp)));
	XMStoreFloat4x4(proj, XMMatrixTranspose(XMMatrixOrthographicRH(width, height, 0.01f, 125.0f)));
}
Example #11
0
		void SampleRenderer::Initialize()
		{
			m_RenderQueue = new ::Dispatch::WorkQueue("RenderQueue", ::Concurrency::ThreadPriority::High);
			m_RenderQueue->Loop();
			isInitialized = false;

			float aspectRatio = 1900.f/700;
			float fovAngleY = 70.0f * XM_PI / 180.0f;

			if (aspectRatio < 1.0f)
			{
				fovAngleY *= 2.0f;
			}

			XMMATRIX perspectiveMatrix = XMMatrixPerspectiveFovRH(fovAngleY, aspectRatio, 0.01f, 100.0f);
			XMStoreFloat4x4(&m_MVP.projection, XMMatrixTranspose(perspectiveMatrix));

			static const XMVECTORF32 eye = { 0.0f, 0.7f, 1.5f, 0.0f };
			static const XMVECTORF32 at = { 0.0f, -0.1f, 0.0f, 0.0f };
			static const XMVECTORF32 up = { 0.0f, 1.0f, 0.0f, 0.0f };
			XMStoreFloat4x4(&m_MVP.model, XMMatrixTranspose(XMMatrixRotationY(1.57)));
			XMStoreFloat4x4(&m_MVP.view, XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up)));

			auto d3dDevice = gD3DDevice->GetD3DDevice();


			CD3DX12_ROOT_PARAMETER parameter[3];

			CD3DX12_DESCRIPTOR_RANGE range;
			range.Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0);
			parameter[0].InitAsDescriptorTable(1, &range, D3D12_SHADER_VISIBILITY_VERTEX);

			CD3DX12_DESCRIPTOR_RANGE range2;
			range2.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);
			parameter[1].InitAsDescriptorTable(1, &range2, D3D12_SHADER_VISIBILITY_PIXEL);

			CD3DX12_DESCRIPTOR_RANGE range3;
			range3.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0);
			parameter[2].InitAsDescriptorTable(1, &range3, D3D12_SHADER_VISIBILITY_PIXEL);

			D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags =
				D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
				D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
				D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
				D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
				D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;

			CD3DX12_ROOT_SIGNATURE_DESC descRootSignature;
			descRootSignature.Init(3, parameter, 0, nullptr, rootSignatureFlags);

			PtrBlob pSignature, pError;
			ThrowIfFailed(D3D12SerializeRootSignature(&descRootSignature, D3D_ROOT_SIGNATURE_VERSION_1, pSignature.GetInitReference(), pError.GetInitReference()));
			ThrowIfFailed(d3dDevice->CreateRootSignature(0, pSignature->GetBufferPointer(), pSignature->GetBufferSize(), IID_PPV_ARGS(m_RootSignature.GetInitReference())));
			
			m_CopyQueue = new CopyQueue_tr(d3dDevice);
			m_CopyQueue->StartLoop();


			m_RenderQueue->Queue(::Dispatch::Bind([this, d3dDevice]() {
				m_VS.Load("/Data/Test/Test.vso");
				m_PS.Load("/Data/Test/Test.pso");

				static const D3D12_INPUT_ELEMENT_DESC inputLayout[] =
				{
					{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
					{ "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
				};

				D3D12_GRAPHICS_PIPELINE_STATE_DESC state = {};
				state.InputLayout = { inputLayout, _countof(inputLayout) };
				state.pRootSignature = m_RootSignature;
				state.VS = { m_VS.GetBlob()->GetBufferPointer(), m_VS.GetBlob()->GetBufferSize() };
				state.PS = { m_PS.GetBlob()->GetBufferPointer(), m_PS.GetBlob()->GetBufferSize() };
				state.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
				state.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
				state.DepthStencilState.DepthEnable = FALSE;
				state.DepthStencilState.StencilEnable = FALSE;
				state.SampleMask = UINT_MAX;
				state.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
				state.NumRenderTargets = 1;
				state.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
				state.SampleDesc.Count = 1;

				ThrowIfFailed(d3dDevice->CreateGraphicsPipelineState(&state, IID_PPV_ARGS(m_PipeLineState.GetInitReference())));

				LogUtil::Out("Renderer", ::Concurrency::Thread::GetCurrentThreadName());

			}));

			m_RenderQueue->Queue(::Dispatch::Bind([this, d3dDevice]() {
				ThrowIfFailed(d3dDevice->CreateCommandList(1, D3D12_COMMAND_LIST_TYPE_DIRECT, gD3DDevice->GetCommandAllocator(), m_PipeLineState, IID_PPV_ARGS(m_CmdList.GetInitReference())));

				D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
				heapDesc.NumDescriptors = DeviceManager::GetFrameCount();
				heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
				heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
				ThrowIfFailed(d3dDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(m_CBVHeap.GetInitReference())));
				m_CBVHeap->SetName(L"Constant Buffer Heap");
				
				m_samplerHeap.Create(d3dDevice, D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true);
				D3D12_SAMPLER_DESC samplerDesc = {};
				samplerDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
				samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
				samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
				samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
				samplerDesc.MipLODBias = 0.0f;
				samplerDesc.MaxAnisotropy = 1;
				samplerDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
				samplerDesc.MinLOD = 0;
				samplerDesc.MaxLOD = D3D12_FLOAT32_MAX;
				d3dDevice->CreateSampler(&samplerDesc, m_samplerHeap.hCPU(0));

				m_CubeMesh = new CubeMesh(d3dDevice, m_CmdList);

				this->m_CopyQueue->SubmitTexture(L"\\Data\\Test\\seafloor2bc1.dds", m_CubeMesh);

				m_CBO = new UniformBuffer<ModelViewProjectionConstantBuffer>("ModeViewMatrix", d3dDevice, 1U);
				m_CBO->CreateOnHeap(m_CBVHeap, d3dDevice);

				m_ConstantBuffer = m_CBO->Map();
				ZeroMemory(m_ConstantBuffer, DeviceManager::GetFrameCount() * m_CBO->sAlignedConstantBufferSize);

				ThrowIfFailed(m_CmdList->Close());
				ID3D12CommandList* ppCommandLists[] = { m_CmdList };
				gD3DDevice->GetCommandQueue()->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);
				gD3DDevice->WaitForGPU();

				isInitialized = true; 
			}));
		}
Example #12
0
bool TestTriangleStripsDX::InitScene()
{
	XMStoreFloat4(&up, XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f));
	XMStoreFloat4(&eye, XMVectorSet(0.0f, 18.0f, 18.0f, 1.0f));
	XMStoreFloat4(&right, XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f));
	XMStoreFloat4(&center, XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f));

	bg[0] = bgColor.r;
	bg[1] = bgColor.g;
	bg[2] = bgColor.b;
	bg[3] = bgColor.a;

	ID3D11RasterizerState1 *rasterizerState;
	D3D11_RASTERIZER_DESC1 rasterizerDesc;
	ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));
	rasterizerDesc.CullMode = D3D11_CULL_NONE;
	rasterizerDesc.FillMode = D3D11_FILL_SOLID;
	rasterizerDesc.FrontCounterClockwise = true;

	mDevice->CreateRasterizerState1(&rasterizerDesc, &rasterizerState);
	mDeviceContext->RSSetState(rasterizerState);
	rasterizerState->Release();

	BinaryIO::ReadVector4s(binaryPath + "triangle_strip_plane.bin", vertices);

	D3D11_INPUT_ELEMENT_DESC vertexLayout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};

	D3DCompileFromFile(Util::s2ws(shaderPath + "TestTriangleStripsVert.hlsl").c_str(), NULL, NULL, "vertexShader", "vs_5_0", NULL, NULL, &vertexShaderBuffer, NULL);
	D3DCompileFromFile(Util::s2ws(shaderPath + "TestTriangleStripsFrag.hlsl").c_str(), NULL, NULL, "pixelShader", "ps_5_0", NULL, NULL, &pixelShaderBuffer, NULL);
	mDevice->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &vertexShader);
	mDevice->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &pixelShader);

	D3D11_BUFFER_DESC vertexBufferDesc;
	ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
	vertexBufferDesc.ByteWidth = vertices.size() * sizeof(Vector4);
	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;

	D3D11_SUBRESOURCE_DATA vertexBufferData;
	ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
	vertexBufferData.pSysMem = &vertices[0];

	mDevice->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &vertexBuffer);

	mDevice->CreateInputLayout(vertexLayout, 1, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &inputLayout);

	// UPLOAD MVP MATRICES
	XMMATRIX modelMatrix = XMMatrixIdentity();
	XMMATRIX viewMatrix = XMMatrixLookAtRH(XMLoadFloat4(&eye), XMLoadFloat4(&center), XMLoadFloat4(&up));
	XMMATRIX projectionMatrix = XMMatrixPerspectiveFovRH(XMConvertToRadians(60.0f), 800 / 800, 1.0f, 500.0f);

	ID3D11Buffer* modelMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, modelMatrix);
	mDeviceContext->VSSetConstantBuffers(modelMatrixBufferSlot, 1, &modelMatrixBuffer);
	modelMatrixBuffer->Release();

	viewMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, viewMatrix);
	mDeviceContext->VSSetConstantBuffers(viewMatrixBufferSlot, 1, &viewMatrixBuffer);
	viewMatrixBuffer->Release();

	ID3D11Buffer* projectionMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, projectionMatrix);
	mDeviceContext->VSSetConstantBuffers(projectionMatrixBufferSlot, 1, &projectionMatrixBuffer);
	projectionMatrixBuffer->Release();

	return true;
}
Example #13
0
void AppTest::PopulateCommandListAsync(uint32_t threadID)
{
	CommandAllocatorArray[threadID]->Reset();

	CommandListArray[threadID]->Reset(CommandAllocatorArray[threadID].Get(), PSO.Get());

	Matrix4 view = Matrix4::LookAt(Vector3(0.0f, 6.0f, 2.0f), Vector3(), Vector3(0.0f, 1.0f, 0.0f));
	Matrix4 proj = Matrix4::Perspective(Math::PiOver4, 1280.0f / 720.0f, 0.1f, 1000.0f);

	XMMATRIX viewXM = XMMatrixLookAtRH(XMVectorSet(0.0f, 20.0f, 50.0f, 1.0f), XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f), XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f));
	XMMATRIX projXM = XMMatrixPerspectiveFovRH(Math::PiOver4, 1280.0f / 720.0f, 1.0f, 10000.0f);

	//Update constant buffer
	CBPerObject perObject;

	void* cbUploadPtr = nullptr;

	const unsigned int start = threadID * (BoxCount / ThreadCount);
	const unsigned int end = start + (BoxCount / ThreadCount);

	//Update the constant buffer view transforms for each object
	for (unsigned int i = start; i < end; i++)
	{
		const float scale = 0.04f * static_cast<float>(i);
		const float timeOffset = 1000.0f;
		const float timeMultiplier = 0.001f;

		XMMATRIX world, invTranspose, worldView, worldViewProj;
		world = XMMatrixScaling(scale, scale, scale) * 
			XMMatrixTranslation(static_cast<float>(i), 0.0f, 0.0f) * 
			XMMatrixRotationY(-static_cast<float>((Timer.GetTotalTime() + timeOffset) * static_cast<float>(i)) * timeMultiplier) * 
			XMMatrixScaling(0.01f, 0.01f, 0.01f);

		worldView = world * viewXM;
		worldViewProj = worldView * projXM;

		memcpy_s(&perObject.World, sizeof(perObject.World), &world, sizeof(world));
		memcpy_s(&perObject.WorldViewProj, sizeof(perObject.WorldViewProj), &worldViewProj, sizeof(worldViewProj));

		//Update the constant buffer data for specified object
		cbUploadPtr = PerObjectConstantBuffers.Map(i);
		memcpy_s(cbUploadPtr, sizeof(CBPerObject), &perObject, sizeof(perObject));
		PerObjectConstantBuffers.Unmap(i);
	}

	if (!UseRootLevelCBV)
	{
		ID3D12DescriptorHeap* descriptorHeap = ConstantBufferDescriptorHeap->GetBaseHeap();
		CommandListArray[threadID]->SetDescriptorHeaps(1, &descriptorHeap);
	}

	CommandListArray[threadID]->SetGraphicsRootSignature(RootSignature.Get());

	CommandListArray[threadID]->RSSetViewports(1, &Viewport);
	CommandListArray[threadID]->RSSetScissorRects(1, &RectScissor);

	SetResourceBarrier(CommandListArray[threadID].Get(), RenderTarget.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);

	CommandListArray[threadID]->OMSetRenderTargets(1, &DescriptorHeap->GetCPUDescriptorHandleForHeapStart(), true, &DSVDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
	CommandListArray[threadID]->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	CommandListArray[threadID]->IASetVertexBuffers(0, 1, &DescViewBufVert);
	CommandListArray[threadID]->IASetIndexBuffer(&DescViewBufIndex);

	D3D12_GPU_DESCRIPTOR_HANDLE descriptorHandle;
	
	if (!UseBundles)
	{
		if (UseRootLevelCBV)
		{
			for (unsigned int i = start; i < end; i++)
			{
				CommandListArray[threadID]->SetGraphicsRootConstantBufferView(0, PerObjectConstantBuffers.GetGPUHandle(i));
				CommandListArray[threadID]->DrawIndexedInstanced(IndexCount, 1, 0, 0, 0);
			}
		}
		else
		{
			for (unsigned int i = start; i < end; i++)
			{
				descriptorHandle.ptr = ConstantBufferDescriptorHeap->GetDescriptorGPUHandle(i);
				CommandListArray[threadID]->SetGraphicsRootDescriptorTable(0, descriptorHandle);
				CommandListArray[threadID]->DrawIndexedInstanced(IndexCount, 1, 0, 0, 0);
			}
		}
	}
	else
	{
		const unsigned int bundleStart = (BundleCount / ThreadCount) * threadID;
		const unsigned int bundleEnd = bundleStart + BundleCount / ThreadCount;

		for (unsigned int i = bundleStart; i < bundleEnd; i++)
		{
			CommandListArray[threadID]->ExecuteBundle(CommandBundleArray[i].Get());
		}
	}

	SetResourceBarrier(CommandListArray[threadID].Get(), RenderTarget.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);

	CommandListArray[threadID]->Close();
}
Example #14
0
bool SuzanneDX::InitScene()
{
	XMStoreFloat4(&up, XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f));
	XMStoreFloat4(&eye, XMVectorSet(3.0f, 3.0f, 5.0f, 1.0f));
	XMStoreFloat4(&right, XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f));
	XMStoreFloat4(&center, XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f));

	ID3D11RasterizerState1 *rasterizerState;
	D3D11_RASTERIZER_DESC1 rasterizerDesc;
	ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));
	rasterizerDesc.CullMode = D3D11_CULL_BACK;
	rasterizerDesc.FillMode = D3D11_FILL_SOLID;
	rasterizerDesc.FrontCounterClockwise = true;

	mDevice->CreateRasterizerState1(&rasterizerDesc, &rasterizerState);
	mDeviceContext->RSSetState(rasterizerState);
	rasterizerState->Release();

	// COMPILE SHADERS
	D3DCompileFromFile(Util::s2ws(shaderPath + "TestSceneVert.hlsl").c_str(), NULL, NULL, "vertexShader", "vs_5_0", NULL, NULL, &vertexShaderBuffer, NULL);
	D3DCompileFromFile(Util::s2ws(shaderPath + "TestSceneFrag.hlsl").c_str(), NULL, NULL, "pixelShader", "ps_5_0", NULL, NULL, &pixelShaderBuffer, NULL);
	mDevice->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &vertexShader);
	mDevice->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &pixelShader);

	D3DCompileFromFile(Util::s2ws(shaderPath + "ShadowMappingVert.hlsl").c_str(), NULL, NULL, "vertexShader", "vs_5_0", NULL, NULL, &shadowVertexShaderBuffer, NULL);
	D3DCompileFromFile(Util::s2ws(shaderPath + "ShadowMappingFrag.hlsl").c_str(), NULL, NULL, "pixelShader", "ps_5_0", NULL, NULL, &shadowPixelShaderBuffer, NULL);
	mDevice->CreateVertexShader(shadowVertexShaderBuffer->GetBufferPointer(), shadowVertexShaderBuffer->GetBufferSize(), NULL, &shadowVertexShader);
	mDevice->CreatePixelShader(shadowPixelShaderBuffer->GetBufferPointer(), shadowPixelShaderBuffer->GetBufferSize(), NULL, &shadowPixelShader);

	// PREPARE MODELS
	std::vector<D3D11_INPUT_ELEMENT_DESC> vertexLayout;
	vertexLayout.push_back({ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 });
	vertexLayout.push_back({ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(Vertex().position), D3D11_INPUT_PER_VERTEX_DATA, 0 });

	XMMATRIX modelMatrix;

	modelMatrix = XMMatrixTranslation(0.0f, 1.0f, 0.0f);
	models.push_back(ModelDX(modelPath + "monkey.bin", modelPath + "monkey2.mtl", mDevice, vertexShaderBuffer, vertexLayout, modelMatrix, true));

	modelMatrix = XMMatrixScaling(5.0f, 5.0f, 5.0f);
	models.push_back(ModelDX(modelPath + "plane.bin", modelPath + "plane.mtl", mDevice, vertexShaderBuffer, vertexLayout, modelMatrix, true));

	// PREPARE LIGHTING
	lighting.ambient = Vector4(0.1f, 0.1f, 0.1f, 1.0f);

	Light light1;
	light1.position = Vector4(-5.0f, 5.0f, 5.0f, 0.0f);
	light1.diffuse = Vector4(0.5f, 0.5f, 0.5f, 1.0f);
	light1.specular = Vector4(0.5f, 0.5f, 0.5f, 1.0f);

	Light light2;
	light2.position = Vector4(5.0f, 5.0f, 5.0f, 0.0f);
	light2.diffuse = Vector4(0.5f, 0.5f, 0.5f, 1.0f);
	light2.specular = Vector4(0.5f, 0.5f, 0.5f, 1.0f);

	lighting.lights[0] = light1;
	lighting.lights[1] = light2;

	D3D11_BUFFER_DESC lightDesc;
	ZeroMemory(&lightDesc, sizeof(lightDesc));
	lightDesc.ByteWidth = sizeof(Lighting);
	lightDesc.Usage = D3D11_USAGE_DEFAULT;
	lightDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	lightDesc.CPUAccessFlags = 0;

	D3D11_SUBRESOURCE_DATA lightData;
	ZeroMemory(&lightData, sizeof(lightData));
	lightData.pSysMem = &lighting;

	ID3D11Buffer* lightBuffer;
	mDevice->CreateBuffer(&lightDesc, &lightData, &lightBuffer);
	mDeviceContext->VSSetConstantBuffers(lightBufferSlot, 1, &lightBuffer);
	mDeviceContext->PSSetConstantBuffers(lightBufferSlot, 1, &lightBuffer);
	lightBuffer->Release();

	RenderShadowMaps();

	D3D11_SAMPLER_DESC samplerDesc;
	ZeroMemory(&samplerDesc, sizeof(samplerDesc));
	samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER;
	samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER;
	samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER;
	samplerDesc.BorderColor[0] = 1.0f;
	samplerDesc.BorderColor[1] = 1.0f;
	samplerDesc.BorderColor[2] = 1.0f;
	samplerDesc.BorderColor[3] = 1.0f;
	samplerDesc.MinLOD = 0.f;
	samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
	samplerDesc.MipLODBias = 0.f;
	samplerDesc.MaxAnisotropy = 0;
	samplerDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL;
	samplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR;

	mDevice->CreateSamplerState(&samplerDesc, &shadowMapSamplerState);

	// PREPARE MATERIAL BUFFER
	D3D11_BUFFER_DESC materialDesc;
	ZeroMemory(&materialDesc, sizeof(materialDesc));
	materialDesc.ByteWidth = sizeof(Material);
	materialDesc.Usage = D3D11_USAGE_DEFAULT;
	materialDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	materialDesc.CPUAccessFlags = 0;

	mDevice->CreateBuffer(&materialDesc, NULL, &materialBuffer);
	mDeviceContext->PSSetConstantBuffers(materialBufferSlot, 1, &materialBuffer);

	// PREPARE VIEW AND PROJECTION
	XMMATRIX viewMatrix = XMMatrixLookAtRH(XMLoadFloat4(&eye), XMLoadFloat4(&center), XMLoadFloat4(&up));
	viewMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, viewMatrix);
	mDeviceContext->VSSetConstantBuffers(viewMatrixBufferSlot, 1, &viewMatrixBuffer);

	XMMATRIX projectionMatrix = XMMatrixPerspectiveFovRH(XMConvertToRadians(60.0f), 800 / 800, 1.0f, 500.0f);
	ID3D11Buffer* projectionMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, projectionMatrix);
	mDeviceContext->VSSetConstantBuffers(projectionMatrixBufferSlot, 1, &projectionMatrixBuffer);
	projectionMatrixBuffer->Release();

	mDeviceContext->PSSetShaderResources(0, 2, &shadowMapResources[0]);
	mDeviceContext->PSSetSamplers(0, 1, &shadowMapSamplerState);

	return true;
}
Example #15
0
void SuzanneDX::RenderShadowMaps()
{
	D3D11_TEXTURE2D_DESC shadowMapDesc;
	ZeroMemory(&shadowMapDesc, sizeof(shadowMapDesc));
	shadowMapDesc.Width = SHADOW_RESOLUTION;
	shadowMapDesc.Height = SHADOW_RESOLUTION;
	shadowMapDesc.MipLevels = 1;
	shadowMapDesc.ArraySize = 1;
	shadowMapDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
	shadowMapDesc.SampleDesc.Count = 1;
	shadowMapDesc.SampleDesc.Quality = 0;
	shadowMapDesc.Usage = D3D11_USAGE_DEFAULT;
	shadowMapDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
	shadowMapDesc.CPUAccessFlags = 0;
	shadowMapDesc.MiscFlags = 0;

	D3D11_DEPTH_STENCIL_VIEW_DESC shadowMapDsvDesc;
	ZeroMemory(&shadowMapDsvDesc, sizeof(shadowMapDsvDesc));
	shadowMapDsvDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	shadowMapDsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	shadowMapDsvDesc.Texture2D.MipSlice = 0;

	D3D11_SHADER_RESOURCE_VIEW_DESC shadowMapResourceDesc;
	ZeroMemory(&shadowMapResourceDesc, sizeof(shadowMapResourceDesc));
	shadowMapResourceDesc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
	shadowMapResourceDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	shadowMapResourceDesc.Texture2D.MipLevels = 1;
	shadowMapResourceDesc.Texture2D.MostDetailedMip = 0;

	D3D11_VIEWPORT shadowMapViewport;
	shadowMapViewport.Width = (FLOAT)SHADOW_RESOLUTION;
	shadowMapViewport.Height = (FLOAT)SHADOW_RESOLUTION;
	shadowMapViewport.MinDepth = 0.0f;
	shadowMapViewport.MaxDepth = 1.0f;
	shadowMapViewport.TopLeftX = 0;
	shadowMapViewport.TopLeftY = 0;
	mDeviceContext->RSSetViewports(1, &shadowMapViewport);

	XMMATRIX shadowViewProjectionMatrices[NUMBER_OF_LIGHTS];
	for (int i = 0; i < NUMBER_OF_LIGHTS; ++i)
	{
		ID3D11Texture2D* shadowMap;
		mDevice->CreateTexture2D(&shadowMapDesc, NULL, &shadowMap);

		ID3D11DepthStencilView* shadowMapDsv;
		mDevice->CreateDepthStencilView(shadowMap, &shadowMapDsvDesc, &shadowMapDsv);

		mDevice->CreateShaderResourceView(shadowMap, &shadowMapResourceDesc, &shadowMapResources[i]);

		mDeviceContext->OMSetRenderTargets(0, 0, shadowMapDsv);
		mDeviceContext->ClearDepthStencilView(shadowMapDsv, D3D11_CLEAR_DEPTH, 1.0f, 0);

		XMVECTOR lightInvDir = XMVector3Normalize(XMVectorSet(lighting.lights[i].position.x, lighting.lights[i].position.y, lighting.lights[i].position.z, 1.0f));
		XMMATRIX shadowProjectionMatrix = XMMatrixOrthographicRH(20, 20, -10, 20);
		XMMATRIX shadowViewMatrix = XMMatrixLookAtRH(lightInvDir, XMVectorSet(0, 0, 0, 1), XMVectorSet(0, 1, 0, 1));
		shadowViewProjectionMatrices[i] = shadowViewMatrix * shadowProjectionMatrix;

		ID3D11Buffer* shadowViewProjectionMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, shadowViewProjectionMatrices[i]);
		mDeviceContext->VSSetConstantBuffers(shadowViewProjectionMatrixBufferSlot, 1, &shadowViewProjectionMatrixBuffer);

		UINT stride = sizeof(Vertex);
		UINT offset = 0;
		for (ModelDX model : models)
		{
			mDeviceContext->IASetVertexBuffers(0, 1, &model.vertexBuffer, &stride, &offset);
			mDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
			mDeviceContext->IASetInputLayout(model.inputLayout);

			mDeviceContext->VSSetShader(shadowVertexShader, 0, 0);
			mDeviceContext->PSSetShader(shadowPixelShader, 0, 0);

			mDeviceContext->VSSetConstantBuffers(modelMatrixBufferSlot, 1, &model.modelMatrixBuffer);

			mDeviceContext->Draw(model.vertexCount, 0);
		}

		shadowMap->Release();
		shadowMapDsv->Release();
		shadowViewProjectionMatrixBuffer->Release();
	}

	mDeviceContext->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView);
	mDeviceContext->RSSetViewports(1, &mViewport);

	D3D11_BUFFER_DESC matrixDesc;
	ZeroMemory(&matrixDesc, sizeof(matrixDesc));
	matrixDesc.ByteWidth = sizeof(XMMATRIX) * NUMBER_OF_LIGHTS;
	matrixDesc.Usage = D3D11_USAGE_DEFAULT;
	matrixDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	matrixDesc.CPUAccessFlags = 0;

	D3D11_SUBRESOURCE_DATA matrixData;
	ZeroMemory(&matrixData, sizeof(matrixData));
	matrixData.pSysMem = &shadowViewProjectionMatrices[0];

	ID3D11Buffer* matrixBuffer;
	mDevice->CreateBuffer(&matrixDesc, &matrixData, &matrixBuffer);

	mDeviceContext->VSSetConstantBuffers(shadowViewProjectionMatrixBufferSlot, 1, &matrixBuffer);
	matrixBuffer->Release();

	XMMATRIX biasMatrix = XMMatrixSet(
		0.5, 0.0, 0.0, 0.0,
		0.0, 0.5, 0.0, 0.0,
		0.0, 0.0, 1.0, 0.0,
		0.5, 0.5, 0.0, 1.0
		);

	ID3D11Buffer* shadowBiasMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, biasMatrix);
	mDeviceContext->VSSetConstantBuffers(shadowBiasMatrixBufferSlot, 1, &shadowBiasMatrixBuffer);
	shadowBiasMatrixBuffer->Release();
}