Esempio n. 1
0
bool processClass::initialize(int width, int height, ID3D11Device *device)
{
	HRESULT hr;
	m_width = width;
	m_height = height;

	camPosition = XMVectorSet(0.0f, 7.0f, -10.0f, 0.0f);
	camTarget = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
	camUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

	//Set the View matrix
	camView = XMMatrixLookAtLH(camPosition, camTarget, camUp);
	camProjection = XMMatrixPerspectiveFovLH(0.4f*XM_PI, (float)width / height, 1.0f, 1000.0f);
	ortho = XMMatrixOrthographicLH((float)width, (float)height, 0.1f, 1000.0f);

	D3D11_BUFFER_DESC cbbd;
	ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));
	cbbd.Usage = D3D11_USAGE_DEFAULT;
	cbbd.ByteWidth = sizeof(cbPerObject);
	cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	cbbd.CPUAccessFlags = 0;
	cbbd.MiscFlags = 0;

	hr = device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);
	return true;
}
Esempio n. 2
0
void D3DCamera::Init(int screenWidth, int screenHeight, ID3D11DeviceContext* devCon, XMVECTOR position, XMVECTOR rotation)
{
	// Setup the viewport
	m_viewport.Width = (float)screenWidth;
	m_viewport.Height = (float)screenHeight;
	m_viewport.MinDepth = 0.0f;
	m_viewport.MaxDepth = 1.0f;
	m_viewport.TopLeftX = 0.0f;
	m_viewport.TopLeftY = 0.0f;

	m_position = position;
	m_rotation = rotation;

	devCon->RSSetViewports(1, &m_viewport);

	// Set up fov to 90°
	m_fieldOfView = PI/4.0f;
	//get Apsect ratio
	m_screenAspect = (float)screenWidth / (float)screenHeight;

	//Set the projection matrix
	m_projectionMatrix = XMMatrixPerspectiveFovLH(m_fieldOfView, m_screenAspect, SCREEN_NEAR, SCREEN_DEPTH);

	//OrthoMatrix
	m_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, SCREEN_NEAR, SCREEN_DEPTH);

}
Esempio n. 3
0
void CascadeShadow::CascadeUpdate(){
	float nearClip = 0.01f;
	float farClip = 100.0f;

	float m_Lamda = 0.8f;

	// 平行分割処理.
	float splitPositions[MAX_CASCADE + 1];
	ComputeSplitPositions(MAX_CASCADE, m_Lamda, nearClip, farClip, splitPositions);

	float SlideBack = 50.0f;

	auto camera = Game::GetMainCamera();
	auto campos = camera->gameObject->mTransform->WorldPosition();
	auto camvec = camera->gameObject->mTransform->Forward();
	float forward = splitPositions[0];

	// カスケード処理.
	for (int i = 0; i<MAX_CASCADE; ++i)
	{
		float size = splitPositions[i + 1] - splitPositions[i + 0];

		auto lightPos = campos + camvec * (forward + size / 2) + mLightVect * -SlideBack;

		m_LightView = XMMatrixLookToLH(lightPos, mLightVect, XMVectorSet(0, 1, 0, 1));

		forward += size;

		float aspect = float(WindowState::mWidth) / float(WindowState::mHeight);
		float fov = XM_PIDIV4;
		float farHeight = tanf(fov) * splitPositions[i + 1];
		float farWidth = farHeight * aspect;

		size = farWidth * 1.41421356f * 1.41421356f;
		m_LightProj = XMMatrixOrthographicLH(size, size, 0.01f, 100.0f);

		// ライトのビュー射影行列.
		m_ShadowMatrix[i] = m_LightView * m_LightProj;

		XMVECTOR min, max;

		// 分割した視錘台の8角をもとめて,ライトのビュー射影空間でAABBを求める.
		CalculateFrustum(
			splitPositions[i + 0],
			splitPositions[i + 1],
			m_ShadowMatrix[i],
			&min,
			&max);

		// クロップ行列を求める.
		XMMATRIX crop = CreateCropMatrix(min, max);

		// シャドウマップ行列と分割位置を設定.
		m_ShadowMatrix[i] = m_ShadowMatrix[i] * crop;
		m_SplitPos[i] = splitPositions[i + 1];
	}
}
Esempio n. 4
0
/**
 *	Create an orthographic projection matrix (left handed)
 *
 *	@param fViewWidth	The width of the view.
 *	@param fViewHeight	The height of the view.
 *	@param fNearZ		The near Z plane distance.
 *	@param fFarZ		The far Z plane distance.
 */
CFMat4x4	CFMat4x4::CreateOrtho( FLOAT32 fViewWidth, FLOAT32 fViewHeight, FLOAT32 fNearZ, FLOAT32 fFarZ )
{
	CFMat4x4 matReturn;
	XMMATRIX& matResult = *reinterpret_cast<XMMATRIX*>( &matReturn );

	matResult = XMMatrixOrthographicLH( fViewWidth, fViewHeight, fNearZ, fFarZ );

	return matReturn;
}
Esempio n. 5
0
	void intiData(){
		people = loadPUBModel("resources/456.BINARY",m_pd3dDevice,m_pImmediateContext);

		
		// Initialize the world matrix
		m_World = XMMatrixIdentity();

		// Initialize the view matrix
		XMVECTOR Eye = XMVectorSet( 0, 1.1, -2.0, 0.0f );
		XMVECTOR At = XMVectorSet( 0.0f, 1.1, 0.0f, 0.0f );
		XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
		m_View = XMMatrixLookAtLH( Eye, At, Up );

		// Initialize the projection matrix
		m_Projection = XMMatrixPerspectiveFovLH( XM_PIDIV4, getWindowWidth() / (FLOAT)getWindowHeight(), 0.01f, 1000.0f );
		m_Projection = XMMatrixOrthographicLH(4,4*getWindowHeight()/(FLOAT)getWindowWidth(),0,100);
		
		bone_shader =new ShaderProgram(m_pd3dDevice);
		bone_shader->setLayout(CUSTOM_LAYOUT_PUB,CUSTOM_LAYOUT_PUB_NUM);
		bone_shader->requestConstantBuffer(192,0);
		bone_shader->requestConstantBuffer(sizeof(XMMATRIX)*BONE_MAX_NUM,1);
		bone_shader->loadShader(L"FX/boneAnime.fx");
		people->useShader(bone_shader);


		Sampler* samp=new Sampler(m_pd3dDevice);
		samp->createSampleState(D3D11_FILTER_MIN_MAG_MIP_LINEAR,D3D11_TEXTURE_ADDRESS_WRAP,-1);
		samp->useSamplerAt(m_pImmediateContext,0);

	//	MyLuaManager::getInstance()->registerFun(ConsleGlue);






		/***********************************************************************/
		
		view_shader= new ShaderProgram(m_pd3dDevice);
		view_shader->setLayout(CUSTOM_LAYOUT_PU,CUSTOM_LAYOUT_PU_NUM);
		view_shader->requestConstantBuffer(192,0);
		view_shader->loadShader(L"FX/Tutorial04.fx");
		quard=new ImageView(m_pd3dDevice);
		quard->setBorder(getWindowWidth(),getWindowHeight());
		quard->setSize(200,150);
		quard->setShader(view_shader);


		backTarget=RenderTarget::generateRenderTarget(m_pd3dDevice,getWindowWidth(),getWindowHeight());
		quard->setTexture(*backTarget->getShaderResource());
		/**********************************************************************/
		setDrawMode(Triangle);
		/*********************************************************************/
		controller=new ObjectController(m_pd3dDevice);
		controller->addObject(quard);
	}
Esempio n. 6
0
//left-handed orthographic projection matrix
aMath::aMat aMath::getOrthMat(float wide,float height,float znear,float zfar)
{
	return XMMatrixOrthographicLH(wide,height,znear,zfar);

	//2/w  0    0           0
    //0    2/h  0           0
    //0    0    1/(zf-zn)   0
    //0    0   -zn/(zf-zn)  1
  
}
Esempio n. 7
0
void DxAssist::SetUICoordinates(ID3D11Buffer* constantBuffer, uint w, uint h)
{
    static XMMATRIX projectionMatrix;

    projectionMatrix = XMMatrixOrthographicLH( (FLOAT)w, -(FLOAT)h, 0.0f, 1.0f );

    ConstantBuffer cb;
    cb.mWorld = XMMatrixTranslation(-(FLOAT)w * 0.5f, -(FLOAT)h * 0.5f, 0.0f);
    cb.mView = XMMatrixIdentity();
    cb.mProjection = projectionMatrix ;

    m_deviceContext->UpdateSubresource( constantBuffer, 0, NULL, &cb, 0, 0 );
    m_deviceContext->VSSetConstantBuffers( 0, 1, &constantBuffer );
}
Esempio n. 8
0
void D3D11Renderer::BuildProjectionMatrices( const DisplaySettings& ds )
{
	*_perspec_mx = XMMatrixPerspectiveFovLH(
		0.25f * XM_PI,
		static_cast< float >( ds._width ) / static_cast< float >( ds._height ),
		0.1f,
		100.0f );

	*_ortho_mx = XMMatrixOrthographicLH(
		static_cast< float >( ds._width ) / 16.0f,
		static_cast< float >( ds._height ) / 16.0f,
		1.0f,
		100.0f );
}
Esempio n. 9
0
	void overlay::init_buffers(int window_width, int window_height)
	{
		D3D11_BUFFER_DESC vertex_desc, index_desc, const_desc;
		D3D11_SUBRESOURCE_DATA vertex_data, index_data;

		std::array<overlay::vertex_t, 6> vertices;
		std::array<uint32_t, 6> indices;

		zero_memory(vertex_desc);
		zero_memory(index_desc);
		zero_memory(const_desc);
		zero_memory(vertex_data);
		zero_memory(index_data);
		zero_memory(vertices);

		auto device = d3d_device::instance()->raw();
		auto context = d3d_device::instance()->get_context();

		for (uint32_t i = 0; i < vertex_count; i++)
			indices[i] = i;

		vertex_desc.Usage = D3D11_USAGE_DYNAMIC;
		vertex_desc.ByteWidth = sizeof(overlay::vertex_t) * vertex_count;
		vertex_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		vertex_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		vertex_data.pSysMem = vertices.data();

		index_desc.ByteWidth = sizeof(uint32_t) * vertex_count;
		index_desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
		index_data.pSysMem = indices.data();

		const_desc.ByteWidth = sizeof(overlay::matrix_t);
		const_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

		device->CreateBuffer(&vertex_desc, &vertex_data, &vertex_buffer);
		device->CreateBuffer(&index_desc, &index_data, &index_buffer);
		device->CreateBuffer(&const_desc, nullptr, &const_buffer);

		overlay::matrix_t matrix_buffer;

		cxmatrix world = XMMatrixIdentity();
		cxmatrix view = XMMatrixLookAtLH(XMVectorZero(), XMVectorSet(0.f, 0.f, 1.f, 0.f), XMVectorSet(0.f, 1.f, 0.f, 0.f));
		cxmatrix ortho = XMMatrixOrthographicLH(static_cast<float>(window_width), static_cast<float>(window_height), 0.1f, 1000.f);

		XMStoreFloat4x4(&matrix_buffer.world, XMMatrixTranspose(world));
		XMStoreFloat4x4(&matrix_buffer.view, XMMatrixTranspose(view));
		XMStoreFloat4x4(&matrix_buffer.ortho, XMMatrixTranspose(ortho));

		context->UpdateSubresource(const_buffer.Get(), 0, nullptr, &matrix_buffer, 0, 0);
	}
Esempio n. 10
0
ASCMatrix4 
ASCDX9Renderer::CreateProjectionMatrix( FLOAT32 fFOV, FLOAT32 fAspect, FLOAT32 fNear, FLOAT32 fFar )
{
	//Assume a LH perspective matrix

	ASCMatrix4 matReturn;
	XMMATRIX matResult;

	//matResult = XMMatrixPerspectiveFovLH(  DegsToRad(fFOV), fAspect, fNear, fFar );
	matResult = XMMatrixOrthographicLH(  fFOV, fAspect, fNear, fFar );

	matReturn = *reinterpret_cast<ASCMatrix4*>(&matResult);

	return matReturn;
}
Esempio n. 11
0
void DirectionalLight::GetVP(Matrix& vp) const
{
	float halfDistance = 10;
	XMVECTOR to = XMVectorSet(0, 0, 0, 0);
	XMVECTOR from = XMLoadFloat3((XMFLOAT3*)&GetTransform().position);

	XMVECTOR eye = XMVectorLerp(to, from, halfDistance);
	XMVECTOR lookat = XMVectorLerp(from, to, halfDistance);

	XMVECTOR up = XMVectorSet(0, 1, 0, 0);

	XMMATRIX v, p;
	v = XMMatrixLookAtLH(eye, lookat, up);
	p = XMMatrixOrthographicLH(20, 20, 1, 100);
	XMStoreFloat4x4((XMFLOAT4X4*)&vp, v * p);
}
// Update frame-based values.
void D3D12Fullscreen::OnUpdate()
{
	const float translationSpeed = 0.0001f;
	const float offsetBounds = 1.0f;

	m_constantBufferData.offset.x += translationSpeed;
	if (m_constantBufferData.offset.x > offsetBounds)
	{
		m_constantBufferData.offset.x = -offsetBounds;
	}

	XMMATRIX transform = XMMatrixMultiply(
		XMMatrixOrthographicLH(m_viewport.Width, m_viewport.Height, 0.0f, 100.0f),
		XMMatrixTranslation(m_constantBufferData.offset.x, 0.0f, 0.0f));

	XMStoreFloat4x4(&m_constantBufferData.transform, XMMatrixTranspose(transform));

	UINT offset = m_frameIndex * sizeof(SceneConstantBuffer);
	memcpy(m_pCbvDataBegin + offset, &m_constantBufferData, sizeof(m_constantBufferData));
}
// Set up the position and rotation of the camera.
bool Camera::Initialize( const XMFLOAT3 &Position, const XMFLOAT3 &Rotation,
	const XMUINT2 &ScreenSize, const XMFLOAT2 &ScreenClipDepth )
{
	SetPosition( Position );
	SetRotation( Rotation );
	float screenWidth = static_cast<float>( ScreenSize.x );
	float screenHeight = static_cast<float>( ScreenSize.y );

	// Setup the projection matrix used to translate the 3D scene 
	// into the 2D viewport space
	float fieldOfView = XM_PIDIV4;
	float screenAspect = screenWidth / screenHeight;

	// Create the projection matrix for 3D rendering.
	m_ProjectionMatrix = XMMatrixPerspectiveFovLH( fieldOfView, screenAspect, ScreenClipDepth.x, ScreenClipDepth.y );

	// Create an orthographic projection matrix for 2D rendering.
	// used for rendering 2D elements like user interfaces on the screen 
	// allowing us to skip the 3D rendering.
	m_OrthoMatrix = XMMatrixOrthographicLH( screenWidth, screenHeight, ScreenClipDepth.x, ScreenClipDepth.y );
	
	return true;
}
Esempio n. 14
0
File: D3D.cpp Progetto: Elbe2/Gundby
bool D3D::CreateViewport(void)
{
	D3D11_VIEWPORT Viewport;
	float FOV;
	float ScreenAspect;
	// Viewport initialisieren
	Viewport.Width = (float)m_pSettings->GetScreenWidth();
	Viewport.Height = (float)m_pSettings->GetScreenHeight();
	Viewport.MinDepth = 0.0f;
	Viewport.MaxDepth = 1.0f;
	Viewport.TopLeftX = 0.0f;
	Viewport.TopLeftY = 0.0f;
	m_DeviceContext->RSSetViewports(1, &Viewport);
	// ProjektionsMatrix erstellen
	FOV = (float)XM_PI / 4.0f;
	ScreenAspect = (float)m_pSettings->GetScreenWidth() / (float)m_pSettings->GetScreenHeight();
	m_ProjectionMatrix = XMMatrixPerspectiveFovLH(FOV, ScreenAspect, m_pSettings->GetScreenNear(), m_pSettings->GetScreenDepth());
	// WorldMatrix
	m_WorldMatrix = XMMatrixIdentity();
	// OrthoMatrix für 2D-Rendering
	m_OrthoMatrix = XMMatrixOrthographicLH((float)m_pSettings->GetScreenWidth(), (float)m_pSettings->GetScreenHeight(), m_pSettings->GetScreenNear(), m_pSettings->GetScreenDepth());

	return true;
}
Esempio n. 15
0
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear){
	HRESULT hr;
	float fov, screenAspect;

	m_vsync_enabled = vsync;
	m_featureLevel = D3D_FEATURE_LEVEL_11_0;

	D3D_DRIVER_TYPE driverTypes[] = {
		D3D_DRIVER_TYPE_HARDWARE,
		D3D_DRIVER_TYPE_WARP,
		D3D_DRIVER_TYPE_REFERENCE,
	};
	UINT numDriverTypes = ARRAYSIZE(driverTypes);
	D3D_FEATURE_LEVEL featureLevels[] = {
		//D3D_FEATURE_LEVEL_11_1,
		D3D_FEATURE_LEVEL_11_0,
		D3D_FEATURE_LEVEL_10_1,
		D3D_FEATURE_LEVEL_10_0,
	};
	UINT numFeatureLevels = ARRAYSIZE(featureLevels);

	for (int driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++){
		m_driverType = driverTypes[driverTypeIndex];
		hr = D3D11CreateDevice(NULL, m_driverType, NULL, 0, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &m_device, &m_featureLevel, &m_deviceContext);
		if (hr == E_INVALIDARG){
			hr = D3D11CreateDevice(NULL, m_driverType, NULL, 0, &featureLevels[1], numFeatureLevels - 1, D3D11_SDK_VERSION, &m_device, &m_featureLevel, &m_deviceContext);
		}
		if (SUCCEEDED(hr)){
			break;
		}
	}
	if (FAILED(hr)){
		return false;
	}

	IDXGIFactory1* factory = 0;
	IDXGIDevice* device = 0;
	hr = m_device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&device));
	if (SUCCEEDED(hr)){
		IDXGIAdapter* adapter = 0;
		hr = device->GetAdapter(&adapter);
		if (SUCCEEDED(hr)){
			hr = adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory));
			adapter->Release();
		}
		device->Release();
	}
	if (FAILED(hr)){
		return false;
	}

	IDXGIFactory2* factory2 = 0;
	hr = factory->QueryInterface(__uuidof(IDXGIFactory2), reinterpret_cast<void**>(&factory2));
	if (factory2){
		hr = m_device->QueryInterface(__uuidof(ID3D11Device1), reinterpret_cast<void**>(&m_device1));
		if (SUCCEEDED(hr)){
			(void)m_deviceContext->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&m_deviceContext1));
		}
		DXGI_SWAP_CHAIN_DESC1 sd;
		ZeroMemory(&sd, sizeof(sd));
		sd.Width = screenWidth;
		sd.Height = screenHeight;
		sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
		sd.SampleDesc.Count = 1;
		sd.SampleDesc.Quality = 0;
		sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
		sd.BufferCount = 1;
		hr = factory2->CreateSwapChainForHwnd(m_device, hwnd, &sd, NULL, NULL, &m_swapChain1);
		if (SUCCEEDED(hr)){
			m_swapChain = NULL;
			hr = m_swapChain1->QueryInterface(__uuidof(IDXGISwapChain), reinterpret_cast<void**>(&m_swapChain));
		}
		factory2->Release();
	}
	else{
		DXGI_SWAP_CHAIN_DESC sd;
		ZeroMemory(&sd, sizeof(sd));
		sd.BufferCount = 1;
		sd.BufferDesc.Width = screenWidth;
		sd.BufferDesc.Height = screenHeight;
		sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
		sd.BufferDesc.RefreshRate.Numerator = 60;
		sd.BufferDesc.RefreshRate.Denominator = 1;
		sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
		sd.OutputWindow = hwnd;
		sd.SampleDesc.Count = 1;
		sd.SampleDesc.Quality = 0;
		sd.Windowed = TRUE;
		hr = factory->CreateSwapChain(m_device, &sd, &m_swapChain);
	}
	factory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER);
	factory->Release();
	if (FAILED(hr)){
		return false;
	}

	ID3D11Texture2D* backBuffer = 0;
	hr = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer));
	if (FAILED(hr)){
		return false;
	}
	hr = m_device->CreateRenderTargetView(backBuffer, NULL, &m_renderTargetView);
	backBuffer->Release();
	if (FAILED(hr)){
		return false;
	}
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, NULL);

	D3D11_TEXTURE2D_DESC depthBufferDesc;
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;
	hr = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
	if (FAILED(hr)){
		return false;
	}

	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	hr = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if (FAILED(hr)){
		return false;
	}
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;
	hr = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
	if (FAILED(hr)){
		return false;
	}
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	D3D11_RASTERIZER_DESC rasterDesc;
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;
	hr = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if (FAILED(hr)){
		return false;
	}
	m_deviceContext->RSSetState(m_rasterState);

	D3D11_VIEWPORT viewport;
	viewport.Width = (float)screenWidth;
	viewport.Height = (float)screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;
	m_deviceContext->RSSetViewports(1, &viewport);

	fov = XM_PI / 4.0f;
	screenAspect = (float)screenWidth / (float)screenHeight;
	m_projectionMatrix = XMMatrixPerspectiveFovLH(fov, screenAspect, screenNear, screenDepth);
	m_worldMatrix = XMMatrixIdentity();
	m_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);
	
	D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
	ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
	depthDisabledStencilDesc.DepthEnable = false;
	depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
	depthDisabledStencilDesc.StencilEnable = true;
	depthDisabledStencilDesc.StencilReadMask = 0xFF;
	depthDisabledStencilDesc.StencilWriteMask = 0xFF;
	depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	hr = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState);
	if (FAILED(hr)){
		return false;
	}

	D3D11_BLEND_DESC blendStateDescription;
	ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));
	blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
	blendStateDescription.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
	blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	//blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_DEST_ALPHA;
	blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
//	blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
	blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;
	hr = m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState);
	if (FAILED(hr)){
		return false;
	}

	blendStateDescription.RenderTarget[0].BlendEnable = FALSE;
	hr = m_device->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState);
	if (FAILED(hr)){
		return false;
	}

	return true;
}
bool D3DManager::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, 
                          float screenDepth, float screenNear) {
    HRESULT result;
    IDXGIFactory* factory;
    IDXGIAdapter* adapter;
    IDXGIOutput* adapterOutput;
    unsigned int numModes, i, numerator, denominator, stringLength;
    DXGI_MODE_DESC* displayModeList;
    DXGI_ADAPTER_DESC adapterDesc;
    int error;
    DXGI_SWAP_CHAIN_DESC swapChainDesc;
    D3D_FEATURE_LEVEL featureLevel;
    ID3D11Texture2D* backBufferPtr;
    D3D11_TEXTURE2D_DESC depthBufferDesc;
    D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    D3D11_RASTERIZER_DESC rasterDesc;
    D3D11_VIEWPORT viewport;
    float fieldOfView, screenAspect;
    D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
    D3D11_BLEND_DESC blendStateDescription;
	std::vector<IDXGIAdapter*> vAdapters;
	int largestAdapter = 0;
	int videoCardMemory;

    // Store our screen width and height
    m_ScreenWidth = screenWidth;
    m_ScreenHeight = screenHeight;

    // Store the vsync setting.
    m_vsync_enabled = vsync;

    // Create a DirectX graphics interface factory.
    result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create a DXGI factory.");
        return false;
    }

	// Loop through each adapter on the computer
	for(UINT i = 0; factory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i)
	{
		// Store the adapter
		vAdapters.push_back(adapter);

		// Get the adapter (video card) description.
		result = adapter->GetDesc(&adapterDesc);
		if(FAILED(result))
		{
			log_sxerror("D3DManager", "Failed to get the video card description.");
			return false;
		}

		// Store the dedicated video card memory in megabytes.
		videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

		// If the memory is larger than our current memory, save this index
		if(videoCardMemory > m_videoCardMemory) {
			m_videoCardMemory = videoCardMemory;
			largestAdapter = i;

			// Convert the name of the video card to a character array and store it.
			error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
			if(error != 0)
			{
				log_sxerror("D3DManager", "Failed to get the name of the graphics card.");
				return false;
			}
		}
	}

    // Enumerate the primary adapter output (monitor).
	result = vAdapters.at(0)->EnumOutputs(0, &adapterOutput);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to grab the monitor.");
        return false;
    }

    // Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
    result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to get a list of display modes.");
        return false;
    }

    // Create a list to hold all the possible display modes for this monitor/video card combination.
    displayModeList = new DXGI_MODE_DESC[numModes];
    if(!displayModeList)
    {
		log_sxerror("D3DManager", "Failed to create a display mode list for the monitor/gfx card combo.");
        return false;
    }

    // Now fill the display mode list structures.
    result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to fill the display mode list structures.");
        return false;
    }

    // Now go through all the display modes and find the one that matches the screen width and height.
    // When a match is found store the numerator and denominator of the refresh rate for that monitor.
    for(i=0; i<numModes; i++)
    {
            if(displayModeList[i].Width == (unsigned int)screenWidth)
            {
                    if(displayModeList[i].Height == (unsigned int)screenHeight)
                    {
                            numerator = displayModeList[i].RefreshRate.Numerator;
                            denominator = displayModeList[i].RefreshRate.Denominator;
                    }
            }
    }

    // Release the display mode list.
    delete [] displayModeList;
    displayModeList = 0;

    // Release the adapter output.
    adapterOutput->Release();
    adapterOutput = 0;

    // Release the factory.
    factory->Release();
    factory = 0;

    // Initialize the swap chain description.
    ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

    // Set to a single back buffer.
    swapChainDesc.BufferCount = 1;

    // Set the width and height of the back buffer.
    swapChainDesc.BufferDesc.Width = screenWidth;
    swapChainDesc.BufferDesc.Height = screenHeight;

    // Set regular 32-bit surface for the back buffer.
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

    // Set the refresh rate of the back buffer.
    if(m_vsync_enabled)
    {
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;//numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;//denominator;
    }
    else
    {
        swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
        swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
    }

    // Set the usage of the back buffer.
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

    // Set the handle for the window to render to.
    swapChainDesc.OutputWindow = hwnd;

    // Turn multisampling off.
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;

    // Set to full screen or windowed mode.
    if(fullscreen)
    {
        swapChainDesc.Windowed = false;
    }
    else
    {
        swapChainDesc.Windowed = true;
    }

    // Set the scan line ordering and scaling to unspecified.
    swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

    // Discard the back buffer contents after presenting.
    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	//swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_SEQUENTIAL;

    // Don't set the advanced flags.
    swapChainDesc.Flags = 0;

    // Grab the highest feature level
	result = D3D11CreateDevice(vAdapters.at(largestAdapter), D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, NULL, 0,
                       D3D11_SDK_VERSION, NULL, &featureLevel, NULL );
	if(FAILED(result))
	{
		log_sxerror("D3DManager", "Failed to retrieve the featurelevel.");
		ErrorDescription(result);

		// Try to use the default adapter
		largestAdapter = 0;

		result = D3D11CreateDevice(vAdapters.at(largestAdapter), D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, NULL, 0,
                       D3D11_SDK_VERSION, NULL, &featureLevel, NULL );
		if(FAILED(result))
		{
			log_sxerror("D3DManager", "Failed to retrieve the featurelevel the second time.");
			ErrorDescription(result);
			return false;
		}
	}

    
#ifdef _DEBUG
	// Create the swap chain, Direct3D device, and Direct3D device context.
	result = D3D11CreateDeviceAndSwapChain(vAdapters.at(largestAdapter), D3D_DRIVER_TYPE_UNKNOWN, NULL, D3D11_CREATE_DEVICE_DEBUG | D3D11_CREATE_DEVICE_BGRA_SUPPORT , &featureLevel, 1, 
                                            D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the Direct3D device, context, and swap chain.");
        return false;
    }

	result = m_device->QueryInterface((IID)IID_ID3D11Debug, (void**)&m_Debug);
	if(FAILED(result))
	{
		log_sxerror("D3DManager", "Failed to create a debugging interface for the device. Debugging may not work");
	} else {
		result = m_Debug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
		if(FAILED(result)) {
			log_sxerror("D3DManager", "Failed to enable detailed object reporting.");
		}	
	}

#else
	// Create the swap chain, Direct3D device, and Direct3D device context.
	result = D3D11CreateDeviceAndSwapChain(vAdapters.at(largestAdapter), D3D_DRIVER_TYPE_UNKNOWN, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT , &featureLevel, 1, 
                                            D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the Direct3D device, context, and swap chain.");
        return false;
    }

#endif

	// Release each adapter.
	for(auto it = vAdapters.begin(); it != vAdapters.end(); ++it)
	{
		(*it)->Release();
		(*it) = 0;
	}

    // Get the pointer to the back buffer.
    result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to get a pointer to the back buffer.");
        return false;
    }

    // Create the render target view with the back buffer pointer.
    result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the render target view.");
        return false;
    }

    // Release pointer to the back buffer as we no longer need it.
    backBufferPtr->Release();
    backBufferPtr = 0;

    // Initialize the description of the depth buffer.
    ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

    // Set up the description of the depth buffer.
    depthBufferDesc.Width = screenWidth;
    depthBufferDesc.Height = screenHeight;
    depthBufferDesc.MipLevels = 1;
    depthBufferDesc.ArraySize = 1;
    depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthBufferDesc.SampleDesc.Count = 1;
    depthBufferDesc.SampleDesc.Quality = 0;
    depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    depthBufferDesc.CPUAccessFlags = 0;
    depthBufferDesc.MiscFlags = 0;

    // Create the texture for the depth buffer using the filled out description.
    result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the depth buffer.");
        return false;
    }

    // Initialize the description of the stencil state.
    ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

    // Set up the description of the stencil state.
    depthStencilDesc.DepthEnable = true;
    depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

    depthStencilDesc.StencilEnable = true;
    depthStencilDesc.StencilReadMask = 0xFF;
    depthStencilDesc.StencilWriteMask = 0xFF;

    // Stencil operations if pixel is front-facing.
    depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Stencil operations if pixel is back-facing.
    depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Create the depth stencil state.
    result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the depth stencil state.");
        return false;
    }

    // Set the depth stencil state.
    m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

    // Initailze the depth stencil view.
    ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

    // Set up the depth stencil view description.
    depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    depthStencilViewDesc.Texture2D.MipSlice = 0;

    // Create the depth stencil view.
    result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the depth stencil view.");
        return false;
    }

    // Bind the render target view and depth stencil buffer to the output render pipeline.
    m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

    // Setup the raster description which will determine how and what polygons will be drawn.
    rasterDesc.AntialiasedLineEnable = false;
    rasterDesc.CullMode = D3D11_CULL_BACK;
    rasterDesc.DepthBias = 0;
    rasterDesc.DepthBiasClamp = 0.0f;
    rasterDesc.DepthClipEnable = true;
    rasterDesc.FillMode = D3D11_FILL_SOLID;
    rasterDesc.FrontCounterClockwise = false;
    rasterDesc.MultisampleEnable = false;
    rasterDesc.ScissorEnable = false;
    rasterDesc.SlopeScaledDepthBias = 0.0f;

    // Create the rasterizer state from the description we just filled out.
    result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the rasterizer state.");
        return false;
    }

    // Now set the rasterizer state.
    m_deviceContext->RSSetState(m_rasterState);

    // Setup the viewport for rendering.
    viewport.Width = (float)screenWidth;
    viewport.Height = (float)screenHeight;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0.0f;
    viewport.TopLeftY = 0.0f;

    // Create the viewport.
    m_deviceContext->RSSetViewports(1, &viewport);

    // Setup the projection matrix.
	fieldOfView = (float)XM_PI / 4.0f;
	assert(screenWidth != 0);
	assert(screenHeight != 0);
    screenAspect = (float)screenWidth / (float)screenHeight;

    // Create the projection matrix for 3D rendering.
	XMStoreFloat4x4(&m_projectionMatrix, XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth));

    // Initialize the world and view matrix to the identity matrix.
    XMStoreFloat4x4(&m_worldMatrix, XMMatrixIdentity());
	XMStoreFloat4x4(&m_viewMatrix, XMMatrixIdentity());

    // Create an orthographic projection matrix for 2D rendering.
    XMStoreFloat4x4(&m_orthoMatrix, XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth));

    // Clear the second depth stencil state before setting the parameters.
    ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));

    // Now create a second depth stencil state which turns off the Z buffer for 2D rendering.  The only difference is 
    // that DepthEnable is set to false, all other parameters are the same as the other depth stencil state.
    depthDisabledStencilDesc.DepthEnable = false;
    depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
    depthDisabledStencilDesc.StencilEnable = true;
    depthDisabledStencilDesc.StencilReadMask = 0xFF;
    depthDisabledStencilDesc.StencilWriteMask = 0xFF;
    depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
    depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Create the state using the device.
    result = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the depth disabled stencil state.");
        return false;
    }

    // Clear the blend state description.
    ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));

    // Create an alpha enabled blend state description.

    blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
    blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
    blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
    blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
    blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
    blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
    blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;

	//blendStateDescription.RenderTarget[0].BlendEnable            = true;
    //blendStateDescription.RenderTarget[0].SrcBlend               = D3D11_BLEND_SRC_COLOR; // This one f***s by adding white
    //blendStateDescription.RenderTarget[0].DestBlend              = D3D11_BLEND_DEST_COLOR; // This one produces fail whale, dusky background, lite trees
    //blendStateDescription.RenderTarget[0].BlendOp                = D3D11_BLEND_OP_ADD;
    //blendStateDescription.RenderTarget[0].SrcBlendAlpha          = D3D11_BLEND_SRC_ALPHA;
    //blendStateDescription.RenderTarget[0].DestBlendAlpha         = D3D11_BLEND_DEST_ALPHA;
    //blendStateDescription.RenderTarget[0].BlendOpAlpha           = D3D11_BLEND_OP_ADD;
    //blendStateDescription.RenderTarget[0].RenderTargetWriteMask  = 7;

    // Create the blend state using the description.
    result = m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the alpha blending state.");
        return false;
    }

    // Modify the description to create an alpha disabled blend state description.
    blendStateDescription.RenderTarget[0].BlendEnable = FALSE;

    // Create the blend state using the description.
    result = m_device->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState);
    if(FAILED(result))
    {
		log_sxerror("D3DManager", "Failed to create the alpha disabled blending state.");
        return false;
    }

    return true;
}
Esempio n. 17
0
/*
 *	Initialize()
 *	brief: This function does all the set up needed for DirectX11.
 *	param screenWidth: The window width.
 *	param screenWidth: The window height.
 *	param vsync: Whether the vsync is activated or not.
 *	param hwnd: The window handler.
 *	param fullscreen: Whether if the fullscreen mode is activated or not.
 *	param screenDepth: The setting to know how far our 3D environment will render.
 *	param screenNear: The setting to know how near our 3D environment will render.
 */
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen,
						float screenFar, float screenNear)
{
	//TODO: Split this function in smaller functions. Also, return an error message if failed the initialization to know the reason.
	HRESULT						  hResult;
	IDXGIFactory*				  dxgiFactory;
	IDXGIAdapter*				  dxgiAdapter;
	IDXGIOutput*				  adapterOutput;
	unsigned int				  numModes, numarator, denominator;
	unsigned long long			  stringLength;
	DXGI_MODE_DESC*				  displayModeList;
	DXGI_ADAPTER_DESC			  adapterDesc;
	int							  error;
	DXGI_SWAP_CHAIN_DESC		  swapChainDesc;
	D3D_FEATURE_LEVEL			  featureLevel;
	ID3D11Texture2D*			  backBufferPntr;
	D3D11_TEXTURE2D_DESC		  depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC	  depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC		  rasterizerDesc;
	D3D11_VIEWPORT				  viewport;
	float						  fieldOfView, screenAspect;

	m_vSyncEnabled = vsync;

	//Create DirectX graphics interface factory.
	hResult = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&dxgiFactory);
	if (FAILED(hResult))
	{
		return false;
	}

	//Use a factory to create an adapter for the primary graphics interface.
	hResult = dxgiFactory->EnumAdapters(0, &dxgiAdapter);
	if (FAILED(hResult))
	{
		return false;
	}

	//Enumerate the primary adapter output (monitor).
	hResult = dxgiAdapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(hResult))
	{
		return false;
	}

	//Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
	hResult = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if (FAILED(hResult))
	{
		return false;
	}

	//Create a list to hold all the possible display modes for this monitor/video card combinations.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if (!displayModeList)
	{
		return false;
	}

	//Fill the display mode list structures.
	hResult = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if (FAILED(hResult))
	{
		return false;
	}

	//Go through all the display modes and find the one that matches the screen width and height.
	//When a match is found store the numerator and denominator of the refresh rate for that monitor.
	for (unsigned int i = 0; i < numModes; i++)
	{
		if (displayModeList[i].Width == (unsigned int)screenWidth)
		{
			if (displayModeList[i].Height == (unsigned int)screenHeight)
			{
				numarator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	//Get the adapter (video card) descriptor.
	hResult = dxgiAdapter->GetDesc(&adapterDesc);
	{
		if (FAILED(hResult))
		{
			return false;
		}
	}

	//Store the dedicated video card memory in megabytes.
	m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024) / 1024; //Not sure if this is like this, but the parenthesis at the end didn't make sence to me.

	//Convert the name of the video card to a character array and store it.
	error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
	if (error != 0)
	{
		return false;
	}

	/*We have stored the numerator and denominator for the refresh rate, and we have video card information, time to release the structures
	  used for that.*/

	//Release display mode list.
	delete[] displayModeList;
	displayModeList = 0;

	//Release the adapter output.
	adapterOutput->Release();
	adapterOutput = nullptr;

	//Release the factory.
	dxgiFactory->Release();
	dxgiFactory = nullptr;

	//With the refresh rate saved, it's time to initialize DirectX.

#pragma region SWAP_CHAIN_DESC_INIT

	//Initialize the swap chain description.
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	//Set a single back buffer.
	swapChainDesc.BufferCount = 1;

	//Set width and height of the back buffer.
	swapChainDesc.BufferDesc.Width = screenWidth;
	swapChainDesc.BufferDesc.Height = screenHeight;

	//Set regular 32-bit surface for the back buffer.
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	//Set the refresh rate of the back buffer, using the refresh rate obtained from before and checking the vsync setting.
	if (m_vSyncEnabled)
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = numarator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	//Set the usage of the back buffer.
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

	//Set the handler of the window to render to.
	swapChainDesc.OutputWindow = hwnd;

	//Turn multi-sampling off. *
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;

	//Set to full screen or windowed mode.
	if (fullscreen)
	{
		swapChainDesc.Windowed = false;
	}
	else
	{
		swapChainDesc.Windowed = true;
	}

	//Set scan line ordering and scaling to unspecified. *
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	//Discard the back buffer content after presenting.
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	//Don't set the advanced flags.
	swapChainDesc.Flags = 0;

#pragma endregion 

	//Set feature level to DirectX. For now will be 11. TODO: Make it variable.
	featureLevel = D3D_FEATURE_LEVEL_11_0;

	//Create the swap chain and the DirectX11 device and device context.
	hResult = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION,
											&swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext);
	if (FAILED(hResult))
	{
		return false;
	}

	//Get the pointer to the back buffer.
	hResult = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPntr);
	if (FAILED(hResult))
	{
		return false;
	}

	//Create the render target view with the back buffer.
	hResult = m_device->CreateRenderTargetView(backBufferPntr, NULL, &m_renderTargetView);
	if (FAILED(hResult))
	{
		return false;
	}

	//Release the pointer to the back buffer as we no longer need it.
	backBufferPntr->Release();
	backBufferPntr = nullptr;

	//Time to set the depth buffer description. Also will attach a stencil buffer.

	//Initialize the description of the back buffer.
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	//Set up the description of the depth buffer.
	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	//Create the texture for the depth buffer using the filled out description.
	hResult = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
	if (FAILED(hResult))
	{
		return false;
	}

	//Time to setup the depth stencil descriptor.
	//Initialize  the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	//Setup the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	//Stencil operation if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	//Stencil operation if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	//Now, with the description filled, let's create the depth stencil state.
	hResult = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if (FAILED(hResult))
	{
		return false;
	}

	//With the depth stencil created we can set it so it takes effect. Here the device context is used for it.
	//Set the depth stencil state.
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

	//Initialize the depth stencil view descriptor.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	//Setup the stencil view descriptor.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	//Create the depth stencil view.
	hResult = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
	if (FAILED(hResult))
	{
		return false;
	}

	//Bind the render target view and depth stencil buffer to the output render pipeline.
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	/*By setting up a raster state we can choose which polygons are rendered and how. With that control
	  we can draw in wire frame mode or draw both faces of the polygon. DirectX has one default raster state but
	  we have no control over it and can't change it unless you create one.*/

	//Setup the raster description that will determine how and what polygons will be rendered.
	rasterizerDesc.AntialiasedLineEnable = false;
	rasterizerDesc.CullMode = D3D11_CULL_BACK;
	rasterizerDesc.DepthBias = 0;
	rasterizerDesc.DepthBiasClamp = 0.0f;
	rasterizerDesc.DepthClipEnable = true;
	rasterizerDesc.FillMode = D3D11_FILL_SOLID; //change for wire frame mode.
	rasterizerDesc.FrontCounterClockwise = false;
	rasterizerDesc.MultisampleEnable = false;
	rasterizerDesc.ScissorEnable = false;
	rasterizerDesc.SlopeScaledDepthBias = 0.0f;

	//Create the rasterizer state from the description.
	hResult = m_device->CreateRasterizerState(&rasterizerDesc, &m_rasterizerState);
	if (FAILED(hResult))
	{
		return false;
	}

	//Set the rasterizer state.
	m_deviceContext->RSSetState(m_rasterizerState);

	/*The viewport also needs to be setup so that Direct3D can map clip space coordinates to the render target space.
	  Set this to be the entire size of the window.*/

	//Setup the view port for rendering.
	viewport.Width = (float)screenWidth;
	viewport.Height = (float)screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	//Create the viewport.
	m_deviceContext->RSSetViewports(1, &viewport);

	//Setup the projection matrix.
	fieldOfView = 3.141592654f / 4.0f; //This here is a fixed number. It may be good to play with it to see what happens.
	screenAspect = (float)screenWidth / (float)screenHeight;

	//Create the projection matrix for 3D rendering.
	m_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenFar);

	//Setup the world matrix.
	m_worldMatrix = XMMatrixIdentity();

	/*Here would be the view matrix, but because it is the matrix which will determine our point of view
	  it seems to be better in the camera class.*/

	/*The last thing to set in the initialize function is the orthographic matrix. This matrix will be used
	  to render the 2D elements (like the GUI) on the screens.*/

	//Create an orthographic projection matrix for 2D rendering.
	m_orthographicMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenFar);

	return true;
}
Esempio n. 18
0
		static Matrix orthographic(float width, float height, float nearZ, float farZ)
		{
			return static_cast<Matrix>(XMMatrixOrthographicLH(width, height, nearZ, farZ));
		}
Esempio n. 19
0
bool Direct3D::Initialize(int _screenWidth, int _screenHeight, bool _vsync, HWND _hwnd, bool _fullscreen, float _screenDepth, float _screenNear, TextClass* _timer)
{
	HRESULT result;
	IDXGIFactory1* factory;
	IDXGIAdapter1* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, i, numerator, denominator, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	D3D_FEATURE_LEVEL featureLevel;
	ID3D11Texture2D* backBufferPtr;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;
	float fieldOfView, screenAspect;
	D3D11_BLEND_DESC blendStateDescription;
	bool success;


	// Store the vsync setting.
	vsync_enabled = _vsync;

	// Create a DirectX graphics interface factory.
	result = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&factory);
	if (FAILED(result))
	{
		return false;
	}

	// Use the factory to create an adapter for the primary graphics interface (video card).
	result = factory->EnumAdapters1(0, &adapter);
	if (FAILED(result))
	{
		return false;
	}

	// Enumerate the primary adapter output (monitor).
	result = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(result))
	{
		return false;
	}

	// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if (FAILED(result))
	{
		return false;
	}

	// Create a list to hold all the possible display modes for this monitor/video card combination.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if (!displayModeList)
	{
		return false;
	}

	// Now fill the display mode list structures.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if (FAILED(result))
	{
		return false;
	}

	// Now go through all the display modes and find the one that matches the screen width and height.
	// When a match is found store the numerator and denominator of the refresh rate for that monitor.
	for (i = 0; i<numModes; i++)
	{
		if (displayModeList[i].Width == (unsigned int)_screenWidth)
		{
			if (displayModeList[i].Height == (unsigned int)_screenHeight)
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	// Get the adapter (video card) description.
	result = adapter->GetDesc(&adapterDesc);
	if (FAILED(result))
	{
		return false;
	}

	// Store the dedicated video card memory in megabytes.
	videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	// Convert the name of the video card to a character array and store it.
	error = wcstombs_s(&stringLength, videoCardDescription, 128, adapterDesc.Description, 128);
	if (error != 0)
	{
		return false;
	}

	// Release the display mode list.
	delete[] displayModeList;
	displayModeList = 0;

	// Release the adapter output.
	adapterOutput->Release();
	adapterOutput = 0;

	// Release the factory.
	factory->Release();
	factory = 0;


	// Initialize the swap chain description.
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	// Set to a single back buffer.
	swapChainDesc.BufferCount = 1;

	// Set the width and height of the back buffer.
	swapChainDesc.BufferDesc.Width = _screenWidth;
	swapChainDesc.BufferDesc.Height = _screenHeight;

	// Set regular 32-bit surface for the back buffer.
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;

	// Set the refresh rate of the back buffer.
	if (vsync_enabled)
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	// Set the usage of the back buffer.
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

	// Set the handle for the window to render to. 
	swapChainDesc.OutputWindow = _hwnd;

	// Turn multisampling off.
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;

	// Set to full screen or windowed mode.
	if (_fullscreen)
	{
		swapChainDesc.Windowed = false;
	}
	else
	{
		swapChainDesc.Windowed = true;
	}

	//// Set the scan line ordering and scaling to unspecified.
	//swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	//swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	//// Discard the back buffer contents after presenting.
	//swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	// Don't set the advanced flags.
	swapChainDesc.Flags = 0;

	// Set the feature level to DirectX 11.
	featureLevel = D3D_FEATURE_LEVEL_11_0;

	// Create the swap chain, Direct3D device, and Direct3D device context.
	result = D3D11CreateDeviceAndSwapChain(adapter,
		D3D_DRIVER_TYPE_UNKNOWN,
		NULL,
		D3D11_CREATE_DEVICE_DEBUG | D3D11_CREATE_DEVICE_BGRA_SUPPORT,
		&featureLevel,
		1,
		D3D11_SDK_VERSION,
		&swapChainDesc,
		&swapChain,
		&device,
		NULL,
		&deviceContext);

	if (FAILED(result))
	{
		return false;
	}

	success = _timer->Initialize(device, adapter, _screenWidth, _screenHeight);
	if (!success)
	{
		return false;
	}

	// Release the adapter.
	adapter->Release();
	adapter = 0;

	// Get the pointer to the back buffer.
	result = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if (FAILED(result))
	{
		return false;
	}

	// Create the render target view with the back buffer pointer.
	result = device->CreateRenderTargetView(backBufferPtr, NULL, &backBuffer);
	if (FAILED(result))
	{
		return false;
	}

	// Release pointer to the back buffer as we no longer need it.
	backBufferPtr->Release();
	backBufferPtr = 0;


	// Initialize the description of the depth buffer.
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	// Set up the description of the depth buffer.
	depthBufferDesc.Width = _screenWidth;
	depthBufferDesc.Height = _screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;


	// Create the texture for the depth buffer using the filled out description.
	result = device->CreateTexture2D(&depthBufferDesc, NULL, &depthStencilBuffer);
	if (FAILED(result))
	{
		return false;
	}


	// Initialize the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// Set up the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the depth stencil state.
	result = device->CreateDepthStencilState(&depthStencilDesc, &depthStencilStateON);
	if (FAILED(result))
	{
		return false;
	}

	depthStencilDesc.DepthEnable = false;
	// Create the depth stencil state.
	result = device->CreateDepthStencilState(&depthStencilDesc, &depthStencilStateOFF);
	if (FAILED(result))
	{
		return false;
	}

	// Set the depth stencil state.
	deviceContext->OMSetDepthStencilState(depthStencilStateON, 1);

	// Initailze the depth stencil view.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
	result = device->CreateDepthStencilView(depthStencilBuffer, &depthStencilViewDesc, &depthStencilView);
	if (FAILED(result))
	{
		return false;
	}

	// Bind the render target view and depth stencil buffer to the output render pipeline.
	deviceContext->OMSetRenderTargets(1, &backBuffer, depthStencilView);

	// Setup the raster description which will determine how and what polygons will be drawn.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_NONE;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	result = device->CreateRasterizerState(&rasterDesc, &rasterState);
	if (FAILED(result))
	{
		return false;
	}

	// Now set the rasterizer state.
	deviceContext->RSSetState(rasterState);

	// Setup the viewport for rendering.
	viewport.Width = (float)_screenWidth;
	viewport.Height = (float)_screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	// Create the viewport.
	deviceContext->RSSetViewports(1, &viewport);

	// Setup the projection matrix.
	fieldOfView = (float)XM_PI / 4.0f;
	screenAspect = (float)_screenWidth / (float)_screenHeight;

	// Create the projection matrix for 3D rendering.
	DirectX::XMStoreFloat4x4(&projectionMatrix, XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, _screenNear, _screenDepth));

	// Create an orthographic projection matrix for 2D rendering.
	DirectX::XMStoreFloat4x4(&orthoMatrix, XMMatrixOrthographicLH((float)_screenWidth, (float)_screenHeight, _screenNear, _screenDepth));

	// Clear the blend state description.
	ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));

	// Create an alpha enabled blend state description.
	blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
	blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_COLOR;
	blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;;
	blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
	blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;

	// Create the blend state using the description.
	result = device->CreateBlendState(&blendStateDescription, &alphaEnableBlendingState);
	if (FAILED(result))
	{
		return false;
	}

	// Modify the description to create an alpha disabled blend state description.
	blendStateDescription.RenderTarget[0].BlendEnable = FALSE;

	// Create the blend state using the description.
	result = device->CreateBlendState(&blendStateDescription, &alphaDisableBlendingState);
	if (FAILED(result))
	{
		return false;
	}

	renderer = new RenderManager();
	if (!renderer)
	{
		return false;
	}
	result = renderer->Initialize(device,XMLoadFloat4x4(&projectionMatrix), _screenWidth, _screenHeight);

	return true;
}
Esempio n. 20
0
int APIENTRY WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow) {

	//DX初期化にはデバイス、コンテキスト、スワップチェインの3つ、加えてレンダリングターゲット
	WindowDevice &window = WindowDevice::getInstance();
	DX11Device &device = DX11Device::getInstance();
	window.Init(hInstance, nCmdShow, TEXT("test window"), 1280, 720, true);
	device.Init(window.getHandle(), window.getWidth(), window.getHeight(), window.getWindowMode());
	// IMGUIの初期化
	ImGui_ImplDX11_Init(window.getHandle(), device.getDevice(), device.getContext());

	GraphicsPipeLine deferredGPL;
	//=====================================================//
	//     頂点データ情報(FarstPass & FinalPass)  1.CreateBufferで生成 2.IASetVertexBuffersで設定 3.Drawで実行(描画)
	//=====================================================//
	//***************宣言********************//
	ID3D11Buffer *vertexbuffer = nullptr;		 // FirstPassBuffer
	ID3D11Buffer *finalvertexbuffer = nullptr;   // FinalPassBuffer
	D3D11_BUFFER_DESC bd;						 // 生成方法(バッファー リソース)
	//***************頂点生成********************//
	// 最初描画用   (FarstPass)
	Vertex4UV vertex[4] = {
		{  100.f,  100.f, 1.0f, 1.0f, 1.0f, 0.0f },
		{ -100.f,  100.f, 1.0f, 1.0f, 0.0f, 0.0f },
		{  100.f, -100.f, 1.0f, 1.0f, 1.0f, 1.0f },
		{ -100.f, -100.f, 1.0f, 1.0f, 0.0f, 1.0f },
	};
    // 最終描画用  (FinalPass)
	Vertex4UV finalvertex[4] = {
		{  1.f,  1.f, 1.0f, 1.0f, 1.0f, 0.0f },
		{ -1.f,  1.f, 1.0f, 1.0f, 0.0f, 0.0f },
		{  1.f, -1.f, 1.0f, 1.0f, 1.0f, 1.0f },
		{ -1.f, -1.f, 1.0f, 1.0f, 0.0f, 1.0f },
	};
	//***************頂点バッファ設定********************//(BufferDESCに生成方法を格納&CreateBufferで生成まで)
	// FirstPass設定
	ZeroMemory(&bd, sizeof(bd)); // 中身をゼロクリア
	bd.Usage = D3D11_USAGE_DYNAMIC; // バッファーで想定されている読み込みおよび書き込みの方法を識別
	bd.ByteWidth = sizeof(vertex);  // バッファーのサイズ(バイト単位)
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // なんのバッファですか?
	bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // CPUからは書き込みのみ行います
	device.getDevice()->CreateBuffer(&bd, nullptr, &vertexbuffer); // 設定したBufferを生成
	// FinalPass設定
	ZeroMemory(&bd, sizeof(bd)); // 中身をゼロクリア
	bd.Usage = D3D11_USAGE_DYNAMIC; // バッファーで想定されている読み込みおよび書き込みの方法を識別
	bd.ByteWidth = sizeof(finalvertex);  // バッファーのサイズ(バイト単位)
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // なんのバッファですか?
	bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // CPUからは書き込みのみ行います
	device.getDevice()->CreateBuffer(&bd, nullptr, &finalvertexbuffer); // 設定したBufferを生成
	//***************頂点情報を格納していく********************//(BufferDESCに生成方法を格納&CreateBufferで生成まで)
	// FirstPass格納
	D3D11_MAPPED_SUBRESOURCE ms; // Bufferを格納する為にとりあえずロックをかけないといけない。どこまでロックをかける?サブリソース データにアクセスできるようにする
	device.getContext()->Map(vertexbuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); // アクセス先ms
	memcpy(ms.pData, vertex, sizeof(vertex));// pData = vetexコピー 書き込み
	device.getContext()->Unmap(vertexbuffer, NULL); // ロック解除
	// FinalPass格納
	device.getContext()->Map(finalvertexbuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); // アクセス先ms
	memcpy(ms.pData, finalvertex, sizeof(finalvertex));// pData = vetexコピー 書き込み
	device.getContext()->Unmap(finalvertexbuffer, NULL); // ロック解除

	//=====================================================//
	//       シェーダー情報(VertexShader&PixelShader)   1.Create(Vertex & Pixel)Shaderで生成  2.(VS & PS)SetShaderで実行
	//=====================================================//
	//***************宣言********************//
	ID3D11VertexShader *vs_buf = nullptr;       // (first) shaderのbuffer コンパイルしたシェーダーの格納先
	ID3D11PixelShader  *ps_buf = nullptr;       // (first) shaderのbuffer コンパイルしたシェーダーの格納先
	ID3D11VertexShader *vsfinal_buf = nullptr;  // (final) shaderのbuffer コンパイルしたシェーダーの格納先
	ID3D11PixelShader  *psfinal_buf = nullptr;  // (final) shaderのbuffer コンパイルしたシェーダーの格納先
	ID3D10Blob *vsblob, *psblob, *vsblobfinal, *psblobfinal; // 任意長のデータを返す際に使用
	//***************シェーダーコード格納ファイルコンパイル********************//
	D3DX11CompileFromFile(TEXT("./Shader/VSDeferred.hlsl"), 0, 0, "main", "vs_5_0", 0, 0, 0, &vsblob, 0, 0);
	D3DX11CompileFromFile(TEXT("./Shader/PSDeferred.hlsl"), 0, 0, "main", "ps_5_0", 0, 0, 0, &psblob, 0, 0);
	D3DX11CompileFromFile(TEXT("./Shader/VSDeferredFinal.hlsl"), 0, 0, "main", "vs_5_0", 0, 0, 0, &vsblobfinal, 0, 0);
	D3DX11CompileFromFile(TEXT("./Shader/PSDeferredFinal.hlsl"), 0, 0, "main", "ps_5_0", 0, 0, 0, &psblobfinal, 0, 0);
	//***************シェーダーの設定(VS&PS)**********************************//
	device.getDevice()->CreateVertexShader(vsblob->GetBufferPointer(), vsblob->GetBufferSize(), nullptr, &vs_buf); // コンパイル済みシェーダーから、頂点シェーダー オブジェクトを作成
	device.getDevice()->CreatePixelShader(psblob->GetBufferPointer(), psblob->GetBufferSize(), nullptr, &ps_buf);  // ピクセル シェーダーを作成
	device.getDevice()->CreateVertexShader(vsblobfinal->GetBufferPointer(), vsblobfinal->GetBufferSize(), nullptr, &vsfinal_buf); // コンパイル済みシェーダーから、頂点シェーダー オブジェクトを作成
	device.getDevice()->CreatePixelShader(psblobfinal->GetBufferPointer(), psblobfinal->GetBufferSize(), nullptr, &psfinal_buf);  // ピクセル シェーダーを作成
	// 頂点シェーダーをデバイスに設定(実行)
	device.getContext()->VSSetShader(vsfinal_buf, nullptr, 0); // 頂点シェーダーをデバイスに設定
	device.getContext()->PSSetShader(psfinal_buf, nullptr, 0); // ピクセル シェーダーをデバイスに設定

	//=====================================================//
	///            頂点レイアウト情報
	//=====================================================//
	// 入力レイアウト(レイアウト情報をコンパイル済みVertexShaderから動的に構築)
	D3D11_INPUT_ELEMENT_DESC element[] = { // 入力アセンブラー ステージの単一の要素( HLSL セマンティクス,要素のセマンティクス インデックス,要素データのデータ型,入力アセンブラーを識別する整数値,各要素間のオフセット (バイト単位),単一の入力スロットの入力データ クラスを識別,インスタンス単位の同じデータを使用して描画するインスタンスの数)
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },// 位置情報
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 } // UV情報 
	};
	ID3D11InputLayout *inputlayout; // 入力アセンブラー ステージの入力データにアクセス
	device.getDevice()->CreateInputLayout(element, ARRAYSIZE(element), vsblobfinal->GetBufferPointer(), vsblobfinal->GetBufferSize(), &inputlayout); // 格納(入力アセンブラー ステージで使用される入力バッファー データ)
	device.getContext()->IASetInputLayout(inputlayout); //インプットレイアウトの設定 入力アセンブラー ステージに入力レイアウト オブジェクトをバインド
	device.getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); // 頂点の並び方の設定(プリミティブ タイプおよびデータの順序に関する情報をバインド)
	

	// 通常描画用のパイプライン
	CrateDeferredPipeLine(deferredGPL);

	//=====================================================//
	//            カメラ情報
	//=====================================================//
	ConstantBuffer mtx; // Shaderに送る行列の生成
	XMVECTOR hEye = XMVectorSet(0.0f, 0.0f, -2.0f, 0.0f);
	XMVECTOR hAt = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
	XMVECTOR hUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
	mtx.mView = XMMatrixLookAtLH(hEye, hAt, hUp);
	mtx.mWorld = XMMatrixIdentity();
	mtx.mProjection = XMMatrixOrthographicLH((float) window.getWidth(), (float) window.getHeight(), 1, 5000);

	//=====================================================//
	//            コンスタント情報
	//=====================================================//
	//コンテキストバッファ:シェーダーで宣言した定数をプログラム側から変更する(主に生成、更新、シェーダーステージへのセットという3つのアクション)
	// constantバッファ生成
	ID3D11Buffer *constantbuffer = nullptr;
	ZeroMemory(&bd, sizeof(bd)); // 中身をクリア
	// Bufferの生成方法の格納
	bd.ByteWidth = sizeof(ConstantBuffer); // sizeの指定
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; // なんのバッファですか?
	bd.CPUAccessFlags = 0; // CPUからは書き込みのみ行います
	bd.MiscFlags = 0;
	bd.StructureByteStride = sizeof(float);
	device.getDevice()->CreateBuffer(&bd, NULL, &constantbuffer); // バッファの生成

	//=====================================================//
	//           バッファ情報
	//=====================================================//
	// テクスチャの読み込み
	Texture2D tex,tex2;
	tex.LoadFile("./Resource/Lenna.png");
	tex2.LoadFile("./Resource/lenna_normal.png");
	ID3D11ShaderResourceView *srv[] = {
		tex.getSRV(),
		tex2.getSRV()
	};
	device.getContext()->PSSetShaderResources(0, 2, srv); // ピクセル シェーダー ステージにシェーダー リソースの配列をバインド

	// MRT(マルチレンダーターゲット)
	//Gバッファの生成      ジオメトリバッファ(1pass 複数描画 2次元情報として保存:頂点シェーダとピクセルシェーダの間に実行)
	Texture2D GBuffer[4];
	UINT bindflg = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; // リソースをパイプラインにバインドする方法を識別(、バインド フラグは論理和を使って組み合わせることができる)
	GBuffer[0].Create(window.getWidth(), window.getHeight(), D3D11_USAGE_DEFAULT, DXGI_FORMAT_R32G32B32A32_FLOAT, bindflg);	//Albed
	GBuffer[1].Create(window.getWidth(), window.getHeight(), D3D11_USAGE_DEFAULT, DXGI_FORMAT_R32G32B32A32_FLOAT, bindflg);	//Normal
	GBuffer[2].Create(window.getWidth(), window.getHeight(), D3D11_USAGE_DEFAULT, DXGI_FORMAT_R32_FLOAT, bindflg);			//Depth
	GBuffer[3].Create(window.getWidth(), window.getHeight(), D3D11_USAGE_DEFAULT, DXGI_FORMAT_R32G32B32A32_FLOAT, bindflg);	//Diffuse
	// レンダリング時にシェーダーがアクセス可能なサブリソースを指定(ShaderResourceView)
	ID3D11ShaderResourceView *GBufferSRV [] = { 
		GBuffer[0].getSRV(), //  Albed
		GBuffer[1].getSRV(), //  Normal
		GBuffer[2].getSRV(), //  Depth
		GBuffer[3].getSRV(), //  Diffuse
	};
	// レンダリング時にアクセス可能なレンダー ターゲットのサブリソースを識別(Render Target View)
	ID3D11RenderTargetView *GBufferRTV [] = { 
		GBuffer[0].getRTV(), //  Albed
		GBuffer[1].getRTV(), //  Normal
		GBuffer[2].getRTV(), //  Depth
		GBuffer[3].getRTV(), //  Diffuse
	};
	// クリアの際に使用する
	ID3D11ShaderResourceView *NULLSRV[] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
	ID3D11RenderTargetView   *NULLRTV[] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
	// パイプラインの構築
	deferredGPL.setStatus();

	//=====================================================//
	//           ループ処理
	//=====================================================//
	int ret = 0;
	while (ret != WM_QUIT){
		ret = window.MessageLoop();
		float clear [] = { 0.0f, 0.0f, 0.0f, 0.0f };
		// パイプラインのクリア
		device.getContext()->OMSetRenderTargets(8, NULLRTV, nullptr); // レンダーターゲットのクリア
		device.getContext()->PSSetShaderResources(0,8, NULLSRV);      // シェーダーリソースのクリア
		//バックバッファのクリア
		DEBUG(device.getAnotation()->BeginEvent(L"バッファのクリア"));
		device.getContext()->ClearRenderTargetView(device.getRTV(), clear);
		device.getContext()->ClearDepthStencilView(device.getDSV(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
		//GBufferのクリア
		for (auto v : GBufferRTV) {
			device.getContext()->ClearRenderTargetView(v, clear);
		}
		DEBUG(device.getAnotation()->EndEvent());
		//GUIのクリア
		ImGui_ImplDX11_NewFrame();
		// デバッグ情報の出力
		ImGui::Text("Debug Text");
		ImGui::Text("Application.average %.3f ms/frame(%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); // FPS
		//通常描画で使うバッファの更新
		// Bufferに更新をかける (コンスタントバッファを更新)
		device.getContext()->UpdateSubresource(constantbuffer, 0, NULL, &mtx, 0, 0); // CPU によって、マッピング不可能なメモリー内に作成されたサブリソースにメモリーからデータがコピーされる
		// Bufferをパイプラインにセット (シェーダーステージへのセット)
		device.getContext()->VSSetConstantBuffers(0, 1, &constantbuffer); // 頂点シェーダーのパイプライン ステージで使用される定数バッファーを設定

		//通常描画の設定
		device.getContext()->OMSetRenderTargets(4, GBufferRTV, nullptr); // 出力結合ステージに深度ステンシル バッファーをバインド
		UINT stride = sizeof(Vertex4UV); // 頂点のサイズ
		UINT offset = 0;			   // ずれの調整
		device.getContext()->IASetVertexBuffers(0, 1, &vertexbuffer, &stride, &offset); // 入力アセンブラー ステージに頂点バッファーの配列をバインド
		device.getContext()->VSSetShader(vs_buf, nullptr, 0); // 頂点シェーダーをデバイスに設定
		device.getContext()->PSSetShader(ps_buf, nullptr, 0); // ピクセル シェーダーをデバイスに設定

		device.getContext()->IASetInputLayout(inputlayout); // 入力アセンブラー ステージに入力レイアウト オブジェクトをバインド

		//テクスチャの設定
		ID3D11ShaderResourceView *srv [] = { // レンダリング時にシェーダーがアクセス可能なサブリソースを指定
			tex.getSRV(),
			tex2.getSRV()
		};
		device.getContext()->PSSetShaderResources(0, 2, srv); // ピクセル シェーダー ステージにシェーダー リソースの配列をバインド
		device.getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); // プリミティブ タイプおよびデータの順序に関する情報をバインド
		//通常描画
		device.getContext()->Draw(4, 0);// 頂点数:何番目の頂点からやるか

		//ディファードの最終描画の設定
		DEBUG(device.getAnotation()->BeginEvent(L"ディファードの最終合成"));
		ID3D11RenderTargetView *finalrtv [] = {
			device.getRTV(),
		};
		device.getContext()->OMSetRenderTargets(1, finalrtv, nullptr); //  // 出力結合ステージに深度ステンシル バッファーをバインド
		device.getContext()->IASetVertexBuffers(0, 1, &finalvertexbuffer, &stride, &offset);
		device.getContext()->VSSetShader(vsfinal_buf, nullptr, 0); // 頂点シェーダーをデバイスに設定
		device.getContext()->PSSetShader(psfinal_buf, nullptr, 0); // ピクセル シェーダーをデバイスに設定

		device.getContext()->IASetInputLayout(inputlayout); // // 入力アセンブラー ステージに入力レイアウト オブジェクトをバインド
		device.getContext()->PSSetShaderResources(0, 4, GBufferSRV);  // ピクセル シェーダー ステージにシェーダー リソースの配列をバインド
		device.getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); //  // プリミティブ タイプおよびデータの順序に関する情報をバインド
		//ディファードの最終描画
		device.getContext()->Draw(4, 0);// 頂点数:何番目の頂点からやるか
		DEBUG(device.getAnotation()->EndEvent());
		//Guiの描画
		ImGui::Render();
		//バックバッファとフロントバッファの切り替え
		device.getSwapChain()->Present(0, 0);
	}
	//=====================================================//
	//            解放処理
	//=====================================================//
	//ImGuiの終了処理
	ImGui_ImplDX11_Shutdown();
	// マクロリリース
	SAFE_RELEASE(vertexbuffer);
	SAFE_RELEASE(finalvertexbuffer);
	SAFE_RELEASE(vs_buf);
	SAFE_RELEASE(ps_buf);
	SAFE_RELEASE(vsfinal_buf);
	SAFE_RELEASE(psfinal_buf);
	SAFE_RELEASE(inputlayout);
	SAFE_RELEASE(constantbuffer);
	deferredGPL.Release();

	return ret;
}
Esempio n. 21
0
/*
The Initialize function is what does the entire setup of Direct3D for DirectX 11.  
*/
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, 
						  float screenDepth, float screenNear)
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, numerator, denominator, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;  
	D3D_FEATURE_LEVEL featureLevel;
	ID3D11Texture2D* backBufferPtr;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;
	D3D11_VIEWPORT viewport;
	float fieldOfView, screenAspect;

	D3D11_BLEND_DESC blendStateDescription;


	/*
	Before we can initialize Direct3D we have to get the refresh rate from the video card/monitor. 
	Each computer may be slightly different so we will need to query for that information. 
	We query for the numerator and denominator values and then pass them to DirectX during the setup 
	and it will calculate the proper refresh rate. 
	If we don't do this and just set the refresh rate to a default value which may not exist on all 
	computers then DirectX will respond by performing a blit instead of a buffer flip 
	which will degrade performance and give us annoying errors in the debug output. 
	*/
	// Store the vsync setting.
	m_vsync_enabled = vsync;

	// Create a DirectX graphics interface factory.
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if(FAILED(result))
	{
		return false;
	}

	// Use the factory to create an adapter for the primary graphics interface (video card).
	result = factory->EnumAdapters(0, &adapter);
	if(FAILED(result))
	{
		return false;
	}

	// Enumerate the primary adapter output (monitor).
	result = adapter->EnumOutputs(0, &adapterOutput);
	if(FAILED(result))
	{
		return false;
	}

	// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if(FAILED(result))
	{
		return false;
	}

	// Create a list to hold all the possible display modes for this monitor/video card combination.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if(!displayModeList)
	{
		return false;
	}

	// Now fill the display mode list structures.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if(FAILED(result))
	{
		return false;
	}

	// Now go through all the display modes and find the one that matches the screen width and height.
	// When a match is found store the numerator and denominator of the refresh rate for that monitor.
	/*for(i=0; i<numModes; i++)
	{
		if(displayModeList[i].Width == (unsigned int)screenWidth)
		{
			if(displayModeList[i].Height == (unsigned int)screenHeight)
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}*/

	numerator = 800;
	denominator = 600;
	/*
	We now have the numerator and denominator for the refresh rate. 
	The last thing we will retrieve using the adapter is the name of the video card and the 
	amount of memory on the video card. 
	*/

	// Get the adapter (video card) description.
	result = adapter->GetDesc(&adapterDesc);
	if(FAILED(result))
	{
		return false;
	}

	// Store the dedicated video card memory in megabytes.
	m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	// Convert the name of the video card to a character array and store it.
	error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
	if(error != 0)
	{
		return false;
	}

	// Release the display mode list.
	delete [] displayModeList;
	displayModeList = 0;

	// Release the adapter output.
	adapterOutput->Release();
	adapterOutput = 0;

	// Release the adapter.
	adapter->Release();
	adapter = 0;

	// Release the factory.
	factory->Release();
	factory = 0;

	/*
	Now that we have the refresh rate from the system we can start the DirectX initialization. 
	The first thing we'll do is fill out the description of the swap chain. 
	The swap chain is the front and back buffer to which the graphics will be drawn. 
	Generally you use a single back buffer, do all your drawing to it, and then swap it to the 
	front buffer which then displays on the user's screen. That is why it is called a swap chain. 
	*/

	// Initialize the swap chain description.
    ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	// Set to a single back buffer.
    swapChainDesc.BufferCount = 1; //count does not include the front buffer

	// Set the width and height of the back buffer.
    swapChainDesc.BufferDesc.Width = screenWidth;
    swapChainDesc.BufferDesc.Height = screenHeight;

	// Set regular 32-bit surface for the back buffer.
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	/*
	The next part of the description of the swap chain is the refresh rate. 
	The refresh rate is how many times a second it draws the back buffer to the front buffer. 
	If vsync is set to true in our graphicsclass.h header then this will lock the refresh rate 
	to the system settings (for example 60hz). 
	That means it will only draw the screen 60 times a second 
	(or higher if the system refresh rate is more than 60). 
	However if we set vsync to false then it will draw the screen as many times a second as it can, 
	however this can cause some visual artifacts. 
	*/
	// Set the refresh rate of the back buffer.
	if(m_vsync_enabled)
	{
	    swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
	    swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	// Set the usage of the back buffer.
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; //we will be drawing on this buffer

	// Set the handle for the window to render to.
    swapChainDesc.OutputWindow = hwnd;

	// Turn multisampling off.
    swapChainDesc.SampleDesc.Count = 1; //single sample per pixel
    swapChainDesc.SampleDesc.Quality = 0; 

	// Set to full screen or windowed mode.
	if(fullscreen)
	{
		swapChainDesc.Windowed = false;
	}
	else
	{
		swapChainDesc.Windowed = true;
	}

	// Set the scan line ordering and scaling to unspecified.
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// Discard the back buffer contents after presenting.
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	// Don't set the advanced flags.
	swapChainDesc.Flags = 0;

	/*
	After setting up the swap chain description we also need to setup one more variable 
	called the feature level. This variable tells DirectX what version we plan to use. 
	Here we set the feature level to 11.0 which is DirectX 11. 
	*/
	// Set the feature level to DirectX 11.
	featureLevel = D3D_FEATURE_LEVEL_11_0;

	/*
	Now that the swap chain description and feature level have been filled out we can create the swap chain, 
	the Direct3D device, and the Direct3D device context. 
	The Direct3D device and Direct3D device context are very important, they are the 
	interface to all of the Direct3D functions. 
	We will use the device and device context for almost everything from this point forward. 

    Those of you reading this who are familiar with the previous versions of DirectX will 
	recognize the Direct3D device but will be unfamiliar with the new Direct3D device context. 
	Basically they took the functionality of the Direct3D device and split it up into two 
	different devices so you need to use both now. 

    Note that if the user does not have a DirectX 11 video card this function call will 
	fail to create the device and device context. 
	Also if you are testing DirectX 11 functionality yourself and don't have a 
	DirectX 11 video card then you can replace D3D_DRIVER_TYPE_HARDWARE with 
	D3D_DRIVER_TYPE_REFERENCE and DirectX will use your CPU to draw instead 
	of the video card hardware. 
	Note that this runs 1/1000 the speed but it is good for people who don't 
	have DirectX 11 video cards yet on all their machines. 
	*/
	// Create the swap chain, Direct3D device, and Direct3D device context.
	result = D3D11CreateDeviceAndSwapChain(
		 NULL,   //use default graphics adapter
		 D3D_DRIVER_TYPE_HARDWARE, //hardware graphics acceleration
		 NULL, //no software driver, we are using hardward driver
		 0, //set up for single threaded use
		 &featureLevel, //pointer to D3D feature levels array (enum)
		 1, //number of elements in previous parameter
		 D3D11_SDK_VERSION, //macro to set DirectX SDK version number correctly
		 &swapChainDesc, //pointer to our swap chain description based on our window
		 &m_swapChain, // out: set our m_swapCain pointer
		 &m_device,    //out: set our m_device pointer
		 NULL,       //out: ptr to D3D_FEATURE_LEVEL of created device
		 &m_deviceContext); //out: set our m_device_context pointer

	if(FAILED(result))
	{
		return false;
	}

	/*
	Now that we have a swap chain we need to get a pointer to the back buffer and then attach it to the swap chain. 
	We'll use the CreateRenderTargetView function to attach the back buffer to our swap chain. 
	*/
	// Get the pointer to the back buffer.
	result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if(FAILED(result))
	{
		return false;
	}

	// Create the render target view with the back buffer pointer.
	result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
	if(FAILED(result))
	{
		return false;
	}



	// Release pointer to the back buffer as we no longer need it.
	backBufferPtr->Release();
	backBufferPtr = 0;

	/*
	We will also need to set up a depth buffer description. 
	We'll use this to create a depth buffer so that our polygons can be rendered properly in 3D space. 
	At the same time we will attach a stencil buffer to our depth buffer. 
	The stencil buffer can be used to achieve effects such as motion blur, volumetric shadows, and other things. 
	*/
	// Initialize the description of the depth buffer.
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	// Set up the description of the depth buffer.
	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	/*
	Create the depth/stencil buffer using that description. 
	You will notice we use the CreateTexture2D function to make the buffers, hence the buffer is just a 2D texture. 
	The reason for this is that once your polygons are sorted and then rasterized they just end up being 
	colored pixels in this 2D buffer. Then this 2D buffer is drawn to the screen. 
	*/
	// Create the texture for the depth buffer using the filled out description.
	result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
	if(FAILED(result))
	{
		return false;
	}

	/*
	Now we need to setup the depth stencil description. 
	This allows us to control what type of depth test Direct3D will do for each pixel. 
	*/
	// Initialize the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// Set up the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	/*
	With the description filled out we can now create a depth stencil state. 
	*/
	// Create the depth stencil state.
	result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if(FAILED(result))
	{
		return false;
	}

	/*
	With the created depth stencil state we can now set it so that it takes effect. Notice we use the device context to set it. 
	*/
	// Set the depth stencil state.
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

	/*
	The next thing we need to create is the description of the view of the depth stencil buffer. 
	We do this so that Direct3D knows to use the depth buffer as a depth stencil texture. 
	After filling out the description we then call the function CreateDepthStencilView to create it. 
	*/
	// Initialize the depth stencil view.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
	result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
	if(FAILED(result))
	{
		return false;
	}

	/*
	Now call OMSetRenderTargets. This will bind the render target view and the depth stencil buffer 
	to the output render pipeline. This way the graphics that the pipeline renders will 
	get drawn to our back buffer that we previously created. 
	With the graphics written to the back buffer we can then swap it to the front and display 
	our graphics on the user's screen. 
	*/
	// Bind the render target view and depth stencil buffer to the output render pipeline.
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	/*
	Now that the render targets are setup we can continue on to some extra functions 
	that will give us more control over our scenes for future tutorials. 
	First thing is we'll create is a rasterizer state. This will give us control over how polygons 
	are rendered. We can do things like make our scenes render in wireframe mode or have 
	DirectX draw both the front and back faces of polygons. 
	By default DirectX already has a rasterizer state set up and working 
	the exact same as the one below but you have no control to change it unless you set up one yourself. 
	*/
	// Setup the raster description which will determine how and what polygons will be drawn.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if(FAILED(result))
	{
		return false;
	}

	// Now set the rasterizer state using the device context.
	m_deviceContext->RSSetState(m_rasterState);
	
	/*
	The viewport also needs to be setup so that Direct3D can map clip space coordinates to the render target space. 
	Set this to be the entire size of the window. 
	*/
	// Setup the viewport for rendering.
    viewport.Width = (float)screenWidth;
    viewport.Height = (float)screenHeight;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0.0f;
    viewport.TopLeftY = 0.0f;

	// Create the viewport.
    m_deviceContext->RSSetViewports(1, &viewport);

	/*
	Now we will create the projection matrix. The projection matrix is used to translate the 3D scene 
	into the 2D viewport space that we previously created. 
	We will need to keep a copy of this matrix so that we can pass it to our shaders that will be used to render our scenes. 
	*/
	// Setup the projection matrix.
	fieldOfView = (float)XM_PI / 4.0f;
	screenAspect = (float)screenWidth / (float)screenHeight;

	// Create the projection matrix for 3D rendering.
	XMStoreFloat4x4(&m_projectionMatrix, XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth));

	/*
	We will also create another matrix called the world matrix. This matrix is used to convert the vertices of our 
	objects into vertices in the 3D scene. This matrix will also be used to rotate, translate, 
	and scale our objects in 3D space. From the start we will just initialize the matrix to the 
	identity matrix and keep a copy of it in this object. The copy will be needed to be passed 
	to the shaders for rendering also.
	*/
    // Initialize the world matrix to the identity matrix.
	XMStoreFloat4x4(&m_worldMatrix, XMMatrixIdentity());

	/*
	And the final thing we will setup in the Initialize function is an orthographic projection matrix. 
	This matrix is used for rendering 2D elements like user interfaces on the screen allowing us to skip the 3D rendering. 
	You will see this used in later tutorials when we look at rendering 2D graphics and fonts to the screen. 
	*/
	// Create an orthographic projection matrix for 2D rendering.
	XMStoreFloat4x4(&m_orthoMatrix, XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth));
//	blendStateDescription.AlphaToCoverageEnable = TRUE;

	
	// Clear the blend state description.
	ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));

	// Create an alpha enabled blend state description.
	blendStateDescription.AlphaToCoverageEnable = true;
	blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
    blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
    blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
    blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
    blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blendStateDescription.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;//0x0f;

	// Create the blend state using the description.
	result = m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState);
	if(FAILED(result))
	{
		return false;
	}
	float blendFactor[4] = {0.0f, 0.0f, 0.0f, 0.0f};
	m_deviceContext->OMSetBlendState(m_alphaEnableBlendingState, NULL, 0xFFFFFFFF);
	
    return true;
}
Esempio n. 22
0
File: D3D.cpp Progetto: Elbe2/Gundby
bool D3D::Initialize(HWND hWnd, Settings *pSettings)
{
	HRESULT result;
	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* adapterOutput;
	unsigned int numModes, i, numerator, denominator;
	unsigned long long stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	D3D_FEATURE_LEVEL featureLevel;
	ID3D11Texture2D* backBufferPtr;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;
	D3D11_VIEWPORT viewport;
	float fieldOfView, screenAspect;

	m_pSettings = pSettings;
	m_hWnd = hWnd;

	// Create a DirectX graphics interface factory.
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if (FAILED(result))
	{
		return false;
	}

	// Use the factory to create an adapter for the primary graphics interface (video card).
	result = factory->EnumAdapters(0, &adapter);
	if (FAILED(result))
	{
		return false;
	}

	// Enumerate the primary adapter output (monitor).
	result = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(result))
	{
		return false;
	}

	// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if (FAILED(result))
	{
		return false;
	}

	// Create a list to hold all the possible display modes for this monitor/video card combination.
	displayModeList = new DXGI_MODE_DESC[numModes];
	if (!displayModeList)
	{
		return false;
	}

	// Now fill the display mode list structures.
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if (FAILED(result))
	{
		return false;
	}

	// Now go through all the display modes and find the one that matches the screen width and height.
	// When a match is found store the numerator and denominator of the refresh rate for that monitor.
	for (i = 0; i<numModes; i++)
	{
		if (displayModeList[i].Width == (unsigned int)m_pSettings->GetScreenWidth())
		{
			if (displayModeList[i].Height == (unsigned int)m_pSettings->GetScreenHeight())
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	// Get the adapter (video card) description.
	result = adapter->GetDesc(&adapterDesc);
	if (FAILED(result))
	{
		return false;
	}

	// Store the dedicated video card memory in megabytes.
	m_VideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	// Convert the name of the video card to a character array and store it.
	error = wcstombs_s(&stringLength, m_VideoCardDescription, 128, adapterDesc.Description, 128);
	if (error != 0)
	{
		return false;
	}

	// Release the display mode list.
	delete[] displayModeList;
	displayModeList = 0;

	// Release the adapter output.
	adapterOutput->Release();
	adapterOutput = 0;

	// Release the adapter.
	adapter->Release();
	adapter = 0;

	// Release the factory.
	factory->Release();
	factory = 0;

	// Initialize the swap chain description.
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	// Set to a single back buffer.
	swapChainDesc.BufferCount = 1;

	// Set the width and height of the back buffer.
	swapChainDesc.BufferDesc.Width = m_pSettings->GetScreenWidth();
	swapChainDesc.BufferDesc.Height = m_pSettings->GetScreenHeight();

	// Set regular 32-bit surface for the back buffer.
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	// Set the refresh rate of the back buffer.
	if (m_pSettings->GetVSync())
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	// Set the usage of the back buffer.
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

	// Set the handle for the window to render to.
	swapChainDesc.OutputWindow = hWnd;

	// Turn multisampling off.
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;

	// Set to full screen or windowed mode.
	if (m_pSettings->GetFullscreen())
	{
		swapChainDesc.Windowed = false;
	}
	else
	{
		swapChainDesc.Windowed = true;
	}

	// Set the scan line ordering and scaling to unspecified.
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// Discard the back buffer contents after presenting.
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	// Don't set the advanced flags.
	swapChainDesc.Flags = 0;

	// Set the feature level to DirectX 11.
	featureLevel = D3D_FEATURE_LEVEL_11_0;

	// Create the swap chain, Direct3D device, and Direct3D device context.
	result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_SwapChain, &m_Device, NULL, &m_DeviceContext);
	if (FAILED(result))
	{
		return false;
	}

	// Get the pointer to the back buffer.
	result = m_SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if (FAILED(result))
	{
		return false;
	}

	// Create the render target view with the back buffer pointer.
	result = m_Device->CreateRenderTargetView(backBufferPtr, NULL, &m_RenderTargetView);
	if (FAILED(result))
	{
		return false;
	}

	// Release pointer to the back buffer as we no longer need it.
	backBufferPtr->Release();
	backBufferPtr = 0;

	// Initialize the description of the depth buffer.
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	// Set up the description of the depth buffer.
	depthBufferDesc.Width = m_pSettings->GetScreenWidth();
	depthBufferDesc.Height = m_pSettings->GetScreenHeight();
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	// Create the texture for the depth buffer using the filled out description.
	result = m_Device->CreateTexture2D(&depthBufferDesc, NULL, &m_DepthStencilBuffer);
	if (FAILED(result))
	{
		return false;
	}

	// Initialize the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// Set up the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing.
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing.
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the depth stencil state.
	result = m_Device->CreateDepthStencilState(&depthStencilDesc, &m_DepthStencilState);
	if (FAILED(result))
	{
		return false;
	}

	// Set the depth stencil state.
	m_DeviceContext->OMSetDepthStencilState(m_DepthStencilState, 1);

	// Initialize the depth stencil view.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
	result = m_Device->CreateDepthStencilView(m_DepthStencilBuffer, &depthStencilViewDesc, &m_DepthStencilView);
	if (FAILED(result))
	{
		return false;
	}

	// Bind the render target view and depth stencil buffer to the output render pipeline.
	m_DeviceContext->OMSetRenderTargets(1, &m_RenderTargetView, m_DepthStencilView);

	// Setup the raster description which will determine how and what polygons will be drawn.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	result = m_Device->CreateRasterizerState(&rasterDesc, &m_RasterState);
	if (FAILED(result))
	{
		return false;
	}

	// Now set the rasterizer state.
	m_DeviceContext->RSSetState(m_RasterState);

	// Setup the viewport for rendering.
	viewport.Width = (float)m_pSettings->GetScreenWidth();
	viewport.Height = (float)m_pSettings->GetScreenHeight();
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	// Create the viewport.
	m_DeviceContext->RSSetViewports(1, &viewport);

	// Setup the projection matrix.
	fieldOfView = 3.141592654f / 4.0f;
	screenAspect = (float)m_pSettings->GetScreenWidth() / (float)m_pSettings->GetScreenHeight();

	// Create the projection matrix for 3D rendering.
	m_ProjectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, m_pSettings->GetScreenNear(), m_pSettings->GetScreenDepth());

	// Initialize the world matrix to the identity matrix.
	m_WorldMatrix = XMMatrixIdentity();

	// Create an orthographic projection matrix for 2D rendering.
	m_OrthoMatrix = XMMatrixOrthographicLH((float)m_pSettings->GetScreenWidth(), (float)m_pSettings->GetScreenHeight(), m_pSettings->GetScreenNear(), m_pSettings->GetScreenDepth());

	return true;
}
void GCamera::InitOrthoMatrix(const float clientWidth, const float clientHeight,
	const float nearZ, const float fartherZ)
{
	XMStoreFloat4x4(&mOrtho, XMMatrixOrthographicLH(clientWidth, clientHeight, nearZ, fartherZ));
}
Esempio n. 24
0
void MatrixStack::Ortho(float width,float height,float znear,float zfar){
	m_Projection=XMMatrixOrthographicLH(width,height,znear,zfar);
}
OrthographicMatrix::OrthographicMatrix(float width, float height, float nearPlane, float farPlane)
{
    XMStoreFloat4x4(&m_projMatrix, XMMatrixOrthographicLH(width, height, nearPlane, farPlane));
}
bool D3DManager::Resize(int screenWidth, int screenHeight, float screenDepth, float screenNear)
{
	if(m_swapChain) {
		m_deviceContext->OMSetRenderTargets(0, 0, 0);

        // Release all outstanding references to the swap chain's buffers.
        m_renderTargetView->Release();

        HRESULT result;
        // Preserve the existing buffer count and format.
        // Automatically choose the width and height to match the client rect for HWNDs.
        result = m_swapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);                                        
        if(FAILED(result))
		{
			log_sxerror("D3DManager", "Failed to resize our buffers.");
			return false;
		}

        // Get buffer and create a render-target-view.
        ID3D11Texture2D* pBuffer;
        result = m_swapChain->GetBuffer(0, __uuidof( ID3D11Texture2D),
                                        (void**) &pBuffer );
        if(FAILED(result))
		{
			log_sxerror("D3DManager", "Failed to get a pointer to the back buffer.");
			return false;
		}

        result = m_device->CreateRenderTargetView(pBuffer, NULL,
                                                    &m_renderTargetView);
        if(FAILED(result))
		{
			log_sxerror("D3DManager", "Failed to recreate the render target view.");
			return false;
		}

        pBuffer->Release();

        m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, NULL );

		// Setup the viewport for rendering.
		D3D11_VIEWPORT viewport;
        viewport.Width = (float)screenWidth;
        viewport.Height = (float)screenHeight;
        viewport.MinDepth = 0.0f;
        viewport.MaxDepth = 1.0f;
        viewport.TopLeftX = 0.0f;
        viewport.TopLeftY = 0.0f;

        // Create the viewport.
        m_deviceContext->RSSetViewports(1, &viewport);

		 // Setup the projection matrix.
		float fieldOfView = (float)XM_PI / 4.0f;
		assert(screenWidth != 0);
		assert(screenHeight != 0);
        float screenAspect = (float)screenWidth / (float)screenHeight;

        // Create the projection matrix for 3D rendering.
        XMStoreFloat4x4(&m_projectionMatrix, XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth));

        // Initialize the world and view matrix to the identity matrix.
        XMStoreFloat4x4(&m_worldMatrix, XMMatrixIdentity());
		XMStoreFloat4x4(&m_viewMatrix, XMMatrixIdentity());

        // Create an orthographic projection matrix for 2D rendering.
        XMStoreFloat4x4(&m_orthoMatrix, XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth));

		// Store our screen dimensions
		m_ScreenWidth = screenWidth;
		m_ScreenHeight = screenHeight;
	}

	return true;
}
Esempio n. 27
0
void eel::OrthographicCamera::SetLens(FLOAT width, FLOAT height, FLOAT nearZ, FLOAT farZ)
{
	UpdateProjection(XMMatrixOrthographicLH(width, height, nearZ, farZ));
}
Esempio n. 28
0
bool graphicD3d::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear)
{
	HRESULT hr;

	IDXGIFactory*			factory;
	IDXGIAdapter*			adapter;
	IDXGIOutput*			adapterOutput;
	UINT					nummodes, numerator, denominator;
	DXGI_MODE_DESC*			displayModelist;
	DXGI_ADAPTER_DESC		adapterDesc;

	DXGI_SWAP_CHAIN_DESC			swapchainDesc;
	D3D11_TEXTURE2D_DESC			depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC		depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC	depthStencilViewDesc;	
	D3D11_RASTERIZER_DESC			rasterDesc;
	D3D11_VIEWPORT					viewport;


	// 수직동기화 설정 ( true / false )
	m_vsync = vsync;

	//DirectX Graphic Infrastructure 인터페이스 팩토리 만들기.
	hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if (FAILED(hr))
		return false;
	
	//첫번째 그래픽 카드 어댑터 만들기.
	hr = factory->EnumAdapters(0, &adapter);
	if (FAILED(hr))
		return false;

	//첫번째 모니터의 어댑터 만들기.
	hr = adapter->EnumOutputs(0, &adapterOutput);
	if (FAILED(hr))
		return false;

	//DXGI_FORMAT_R8G8B8A8_UNORM 모니터 출력 포멧에 맞는 모드의 개수 구하기.
	hr = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &nummodes, NULL);
	if (FAILED(hr))
		return false;

	//사용 가능한 모든 모니터와 그래픽카드 조합을 저장할 리스트 생성.
	displayModelist = new DXGI_MODE_DESC[nummodes];
	if (!displayModelist)
		return false;

	//displayModelist 에 값들 채워넣기.
	hr = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &nummodes, displayModelist);
	if (FAILED(hr))
		return false;

	//그래픽 카드와 모니터의 화면 너비/높이 조합을 찾기 완료.
	//모니터의 refresh rate 의 분모 와 분자 값을 저장.
	for (int i = 0; i < nummodes; i++)
	{
		if (displayModelist[i].Width == (UINT)screenWidth &&
			displayModelist[i].Height == (UINT)screenHeight)
		{
			numerator = displayModelist[i].RefreshRate.Numerator;
			denominator = displayModelist[i].RefreshRate.Denominator;
		}
	}


	/*
	*/


	//그래픽 카드 정보 가져오기.
	hr = adapter->GetDesc(&adapterDesc);
	if (FAILED(hr))
		return false;

	//그래픽 카드 메모리 크기 가져오기. ( MegaBytes )
	m_videoMemory = UINT(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
	
	//그래픽 카드 이름 가져오기.
	lstrcpynW(m_videoDescription, adapterDesc.Description, 128);


	/*
	*/
	// 원하는 정보 조회 끝나면, 해당 리소스들 해제
	delete [] displayModelist;
	displayModelist = nullptr;

	//모니터 출력 어댑터 해제
	adapterOutput->Release();
	adapterOutput = nullptr;

	//그래픽카드 어댑터 해제
	adapter->Release();
	adapter = nullptr;

	//팩토리 해제
	factory->Release();
	factory = nullptr;
	

	/*
		스왑체인 설정
	*/

    ZeroMemory( &swapchainDesc, sizeof( swapchainDesc ) );
	//백버퍼 개수를 1개로 설정.
    swapchainDesc.BufferCount = 1;
	swapchainDesc.BufferDesc.Width = screenWidth;
	swapchainDesc.BufferDesc.Height = screenHeight;
    swapchainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	if (m_vsync) {
		//vsync 수치에 맞춰서 page flip 이 일어난다.
		swapchainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapchainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else {
		//vsync 와 상관없이 최대한 많이 그리게 한다.
		swapchainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapchainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}
	// 백버퍼를 렌더 타겟 용도로 사용 설정.
    swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapchainDesc.OutputWindow = hwnd;
	//멀티샘플링 설정을 안함.
    swapchainDesc.SampleDesc.Count = 1;
    swapchainDesc.SampleDesc.Quality = 0;
	//전체화면 모드 창 모드 설정.
	if (fullscreen) {
		swapchainDesc.Windowed = FALSE;
	}
	else {
		swapchainDesc.Windowed = TRUE;
	}
	//스캔라인 정렬 및 사용여부를 안함 (unspecified) 으로 설정.
	swapchainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapchainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	//출력 후 백버퍼 내용 버림으로 설정.
	swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	//추가 옵션 플랙 사용 안함.
	swapchainDesc.Flags = 0;


	/*
		디바이스 설정
	*/
    UINT createDeviceFlags = 0;
#ifdef _DEBUG
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	//그래픽 카드가 dx11 지원되면  HARDWARE,
	//실패하면 REFERENCE 로 처리된다. ( 속도는 HARDWARE 대비 1/1000 정도 느림 )
    D3D_DRIVER_TYPE driverTypes[] =
    {
        D3D_DRIVER_TYPE_HARDWARE,
        D3D_DRIVER_TYPE_WARP,
        D3D_DRIVER_TYPE_REFERENCE,
    };
    UINT numDriverTypes = ARRAYSIZE( driverTypes );

	//directx 버젼 설정
    D3D_FEATURE_LEVEL featureLevels[] =
    {
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
    };
	UINT numFeatureLevels = ARRAYSIZE( featureLevels );

    

    for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
    {
        m_driverType = driverTypes[driverTypeIndex];
        hr = D3D11CreateDeviceAndSwapChain( NULL, m_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels,
                                            D3D11_SDK_VERSION, &swapchainDesc, &m_swapChain, &m_device, &m_featureLevel, &m_deviceContext );
        if( SUCCEEDED( hr ) )
            break;
    }
    if( FAILED( hr ) )
        return false;



	/*
		렌더타겟뷰 (render target view) 만들기
	*/
    //백버퍼 포인터를 가져오기.
    ID3D11Texture2D* pBackBuffer = NULL;
	hr = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
    if( FAILED( hr ) )
        return false;

	//백버퍼 포인터로 렌더타겟뷰 생성.
    hr = m_device->CreateRenderTargetView( pBackBuffer, NULL, &m_renderTargetView );
    if( FAILED( hr ) )
        return false;

	//렌더타겟 생성되면 백버퍼 포인터 필요없으므로 제거.
    pBackBuffer->Release();
	pBackBuffer = nullptr;



	/*
		깊이버퍼 (depth buffer) 만들기 (옵션)
	*/
	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
	depthBufferDesc.Width = screenWidth;
	depthBufferDesc.Height = screenHeight;
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 1;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	//깊이버퍼 2D텍스쳐 생성
	hr = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilbuffer);
	if (FAILED(hr))
		return false;


	/*
		깊이 스텐실 정의 (옵션)
	*/
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;
	//픽셀 전면부 스텐실 연산 처리
	depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	//픽셀 후면부 스텐실 연산 처리
	depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	
	//깊이 스텐실 상태 생성
	hr = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if (FAILED(hr))
		return false;

	//디바이스 컨텍스트에 깊이 스텐실 상태 적용.
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);
	
	
	/*
		깊이 스텐실 뷰 만들기
	*/
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// 깊이-스텐실 뷰를 생성.
	hr = m_device->CreateDepthStencilView(m_depthStencilbuffer, &depthStencilViewDesc, &m_depthStencilView);
	if (FAILED(hr))
		return false;


	/*
		디바이스 컨텍스트에 렌더타겟뷰 와 깊이스텐실뷰를 적용.
	*/
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

	
	/*
		래스터라이징 설정 (옵션)
		- 도형을 어떻게 그릴지 결정 ( 와이어프레임, 2 side 렌더링 등등.. )
	*/

	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	//디바이스로 래스터라이징 상태 생성.
	hr = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if (FAILED(hr))
		return false;
	
	//디바이스 컨텍스트로 래스터라이징 상태 적용.
	m_deviceContext->RSSetState(m_rasterState);

	

	/*
		뷰포트 생성 
	*/    
	viewport.Width = (FLOAT)screenWidth;
	viewport.Height = (FLOAT)screenHeight;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    m_deviceContext->RSSetViewports( 1, &viewport );


	/*
		투영 행렬 ( projection matrix ) 생성
		- 3d 화면을 2d 뷰포트 공간으로 변환
		- 복사본으로 셰이더에서 사용 할 수 있게 한다.
	*/
	float fieldOfView = (float)XM_PI / 4.0f;
	float screenAspect = (float)screenWidth / (float)screenHeight;

	m_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);


	/*
		월드 행렬 ( world matrix ) 생성
		- 오브젝트들을 3d 좌표로 변환하기 위한 행렬 
		- 이동 / 회전 / 크기 에 사용.
		- 복사본으로 셰이더에 사용 할 수 있게 한다.
	*/
	// 월드 행렬을 단위 행렬로 초기화
	m_worldMatrix = XMMatrixIdentity();


	/*
		뷰 행렬 ( view matrix )
		- 카메라에서 따로 생성하기 위해 일단 생략.
	*/


	/*
		정사영 행렬 ( Orthographic matix 생성 )
		- 원근감이 없는 행렬
		- 2d 이미지나 UI 등을 표현할 때 사용.
	*/
	// 2D 렌더링에 사용될 정사영 행렬을 생성.
	m_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);
	
	return true;
}
Esempio n. 29
0
	bool DX11::CreateResources(float a_screenNear, float a_screenFar)
	{
		HRESULT result;

		// Create the render target view with the back buffer pointer.
		result = m_pDevice->CreateRenderTargetView(m_pBackBuffer, NULL, &m_pRenderTargetView);
		if (FAILED(result))
		{
			LOG_ERROR("Could not create render target.");
			return false;
		}

		RELEASE(m_pBackBuffer);

		// Initialize the description of the depth buffer.
		D3D11_TEXTURE2D_DESC depthBufferDesc;
		ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

		// Set up the description of the depth buffer.
		depthBufferDesc.Width = m_width;
		depthBufferDesc.Height = m_height;
		depthBufferDesc.MipLevels = 1;
		depthBufferDesc.ArraySize = 1;
		depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
		depthBufferDesc.SampleDesc.Count = 1;
		depthBufferDesc.SampleDesc.Quality = 0;
		depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
		depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
		depthBufferDesc.CPUAccessFlags = 0;
		depthBufferDesc.MiscFlags = 0;

		// Create the texture for the depth buffer using the filled out description.
		result = m_pDevice->CreateTexture2D(&depthBufferDesc, NULL, &m_pDepthStencilBuffer);
		if (FAILED(result))
		{
			LOG_ERROR("Could not create depth buffer texture.");
			return false;
		}

		// Initialize the description of the stencil state.
		D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
		ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

		// Set up the description of the stencil state.
		depthStencilDesc.DepthEnable = true;
		depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
		depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

		depthStencilDesc.StencilEnable = true;
		depthStencilDesc.StencilReadMask = 0xFF;
		depthStencilDesc.StencilWriteMask = 0xFF;

		// Stencil operations if pixel is front-facing.
		depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
		depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
		depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
		depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

		// Stencil operations if pixel is back-facing.
		depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
		depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
		depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
		depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

		// Create the depth stencil state.
		result = m_pDevice->CreateDepthStencilState(&depthStencilDesc, &m_pDepthStencilState);
		if (FAILED(result))
		{
			LOG_ERROR("Could not create depth stencil state.");
			return false;
		}

		// Set the depth stencil state.
		m_pDeviceContext->OMSetDepthStencilState(m_pDepthStencilState, 1);

		// Initialise the depth stencil view.
		D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
		ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

		// Set up the depth stencil view description.
		depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
		depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
		depthStencilViewDesc.Texture2D.MipSlice = 0;

		// Create the depth stencil view.
		result = m_pDevice->CreateDepthStencilView(m_pDepthStencilBuffer, &depthStencilViewDesc, &m_pDepthStencilView);
		if (FAILED(result))
		{
			LOG_ERROR("Could not create depth stencil view.");
			return false;
		}

		// Bind the render target view and depth stencil buffer to the output render pipeline.
		m_pDeviceContext->OMSetRenderTargets(1, &m_pRenderTargetView, m_pDepthStencilView);

		// Setup the raster description which will determine how and what polygons will be drawn.
		D3D11_RASTERIZER_DESC rasterDesc;
		rasterDesc.AntialiasedLineEnable = false;
		rasterDesc.CullMode = D3D11_CULL_BACK;
		rasterDesc.DepthBias = 0;
		rasterDesc.DepthBiasClamp = 0.0f;
		rasterDesc.DepthClipEnable = true;
		rasterDesc.FillMode = D3D11_FILL_SOLID;
		rasterDesc.FrontCounterClockwise = false;
		rasterDesc.MultisampleEnable = false;
		rasterDesc.ScissorEnable = false;
		rasterDesc.SlopeScaledDepthBias = 0.0f;

		// Create the rasterizer state from the description we just filled out.
		result = m_pDevice->CreateRasterizerState(&rasterDesc, &m_pRasterState);
		if (FAILED(result))
		{
			LOG_ERROR("Could not create rasterizer state.");
			return false;
		}

		// Now set the rasterizer state.
		m_pDeviceContext->RSSetState(m_pRasterState);

		// Setup the viewport for rendering.
		D3D11_VIEWPORT viewport;
		viewport.Width = (float) m_width;
		viewport.Height = (float) m_height;
		viewport.MinDepth = 0.0f;
		viewport.MaxDepth = 1.0f;
		viewport.TopLeftX = 0.0f;
		viewport.TopLeftY = 0.0f;

		// Create the viewport.
		m_pDeviceContext->RSSetViewports(1, &viewport);

		// Setup the projection matrix.
		float fieldOfView = (float) XM_PI / 4.0f;
		float screenAspect = (float) m_width / (float) m_height;

		// Create the projection matrix for 3D rendering.
		m_projMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, a_screenNear, a_screenFar);

		// Initialize the world matrix to the identity matrix.
		m_worldMatrix = XMMatrixIdentity();

		// Create an orthographic projection matrix for 2D rendering.
		m_orthoMatrix = XMMatrixOrthographicLH((float) m_width, (float) m_height, a_screenNear, a_screenFar);

		return true;
	}
Esempio n. 30
0
	void SpriteBase::OnDraw() {
		auto TexPtr = App::GetApp()->GetResource<TextureResource>(m_TextureResName);
		auto Dev = App::GetApp()->GetDeviceResources();
		auto pD3D11DeviceContext = Dev->GetD3DDeviceContext();
		auto RenderState = Dev->GetRenderState();
		//ワールド行列の決定
		Mat4x4 World;
		World.affineTransformation2D(
			m_Scale,			//スケーリング
			Vec2(0, 0),		//回転の中心(重心)
			m_Rot,				//回転角度
			m_Pos				//位置
		);
		//射影行列の決定
		float w = static_cast<float>(App::GetApp()->GetGameWidth());
		float h = static_cast<float>(App::GetApp()->GetGameHeight());
		Mat4x4 Proj(XMMatrixOrthographicLH(w, h, -1.0, 1.0f));
		//行列の合成
		World *= Proj;
		//コンスタントバッファの準備
		SpriteConstantBuffer sb;
		//エミッシブ加算。
		sb.Emissive = m_Emissive;
		//行列の設定
		sb.World = World;
		//コンスタントバッファの更新
		pD3D11DeviceContext->UpdateSubresource(CBSprite::GetPtr()->GetBuffer(), 0, nullptr, &sb, 0, 0);

		//ストライドとオフセット
		UINT stride = sizeof(VertexPositionColorTexture);
		UINT offset = 0;
		//頂点バッファのセット
		pD3D11DeviceContext->IASetVertexBuffers(0, 1, m_SquareMesh->GetVertexBuffer().GetAddressOf(), &stride, &offset);
		//インデックスバッファのセット
		pD3D11DeviceContext->IASetIndexBuffer(m_SquareMesh->GetIndexBuffer().Get(), DXGI_FORMAT_R16_UINT, 0);

		//描画方法(3角形)
		pD3D11DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

		//コンスタントバッファの設定
		ID3D11Buffer* pConstantBuffer = CBSprite::GetPtr()->GetBuffer();
		ID3D11Buffer* pNullConstantBuffer = nullptr;
		//頂点シェーダに渡す
		pD3D11DeviceContext->VSSetConstantBuffers(0, 1, &pConstantBuffer);
		//ピクセルシェーダに渡す
		pD3D11DeviceContext->PSSetConstantBuffers(0, 1, &pConstantBuffer);
		//シェーダの設定
		pD3D11DeviceContext->VSSetShader(VSPCTSprite::GetPtr()->GetShader(), nullptr, 0);
		pD3D11DeviceContext->PSSetShader(PSPCTSprite::GetPtr()->GetShader(), nullptr, 0);
		//インプットレイアウトの設定
		pD3D11DeviceContext->IASetInputLayout(VSPCTSprite::GetPtr()->GetInputLayout());
		//ブレンドステート
		switch (m_BlendState) {
		case BlendState::Opaque:
			pD3D11DeviceContext->OMSetBlendState(RenderState->GetOpaque(), nullptr, 0xffffffff);
			break;
		case BlendState::Trace:
			pD3D11DeviceContext->OMSetBlendState(RenderState->GetAlphaBlendEx(), nullptr, 0xffffffff);
			break;
		case BlendState::Additive:
			pD3D11DeviceContext->OMSetBlendState(RenderState->GetAdditive(), nullptr, 0xffffffff);
			break;
		}
		//デプスステンシルステート
		pD3D11DeviceContext->OMSetDepthStencilState(RenderState->GetDepthNone(), 0);
		//ラスタライザステート
		pD3D11DeviceContext->RSSetState(RenderState->GetCullBack());

		//テクスチャとサンプラーの設定
		ID3D11ShaderResourceView* pNull[1] = { 0 };
		pD3D11DeviceContext->PSSetShaderResources(0, 1, TexPtr->GetShaderResourceView().GetAddressOf());
		//ラッピングサンプラー
		ID3D11SamplerState* pSampler = RenderState->GetLinearWrap();
		pD3D11DeviceContext->PSSetSamplers(0, 1, &pSampler);

		//描画
		pD3D11DeviceContext->DrawIndexed(m_SquareMesh->GetNumIndicis(), 0, 0);
		//後始末
		Dev->InitializeStates();
	}