예제 #1
0
/* Apply raster setting */
void nlUpdateRasterizeSetting(nlEngineContext& cxt)
{
    ID3D11RasterizerState* rasterizerState;
    cxt.d3dDevice->CreateRasterizerState(&cxt.rasterDesc, &rasterizerState);
    cxt.d3dContext->RSSetState(rasterizerState);
    rasterizerState->Release();
}
예제 #2
0
파일: main.cpp 프로젝트: Atomizer74/AIEMath
HRESULT CreateDeviceD3D(HWND hWnd)
{
    // Setup swap chain
    DXGI_SWAP_CHAIN_DESC sd;
    {
        ZeroMemory(&sd, sizeof(sd));
        sd.BufferCount = 2;
        sd.BufferDesc.Width = 0;
        sd.BufferDesc.Height = 0;
        sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        sd.BufferDesc.RefreshRate.Numerator = 60;
        sd.BufferDesc.RefreshRate.Denominator = 1;
        sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
        sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
        sd.OutputWindow = hWnd;
        sd.SampleDesc.Count = 1;
        sd.SampleDesc.Quality = 0;
        sd.Windowed = TRUE;
        sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    }

    UINT createDeviceFlags = 0;
#ifdef _DEBUG
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
    D3D_FEATURE_LEVEL featureLevel;
    const D3D_FEATURE_LEVEL featureLevelArray[1] = { D3D_FEATURE_LEVEL_11_0, };
    if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 1, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
        return E_FAIL;

    // Setup rasterizer
    {
        D3D11_RASTERIZER_DESC RSDesc;
        memset(&RSDesc, 0, sizeof(D3D11_RASTERIZER_DESC));
        RSDesc.FillMode = D3D11_FILL_SOLID;
        RSDesc.CullMode = D3D11_CULL_NONE;
        RSDesc.FrontCounterClockwise = FALSE;
        RSDesc.DepthBias = 0;
        RSDesc.SlopeScaledDepthBias = 0.0f;
        RSDesc.DepthBiasClamp = 0;
        RSDesc.DepthClipEnable = TRUE;
        RSDesc.ScissorEnable = TRUE;
        RSDesc.AntialiasedLineEnable = FALSE;
        RSDesc.MultisampleEnable = (sd.SampleDesc.Count > 1) ? TRUE : FALSE;

        ID3D11RasterizerState* pRState = NULL;
        g_pd3dDevice->CreateRasterizerState(&RSDesc, &pRState);
        g_pd3dDeviceContext->RSSetState(pRState);
        pRState->Release();
    }

    CreateRenderTarget();

    return S_OK;
}
예제 #3
0
void D3DClass::ToggleFillMode()
{
	ID3D11RasterizerState * rState;
	D3D11_RASTERIZER_DESC rDesc;
	
	m_deviceContext->RSGetState(&rState);
	rState->GetDesc(&rDesc);

	rDesc.FillMode = (rDesc.FillMode == D3D11_FILL_SOLID) ? D3D11_FILL_WIREFRAME : D3D11_FILL_SOLID;

	m_device->CreateRasterizerState(&rDesc, &rState);
	m_deviceContext->RSSetState(rState);
}
예제 #4
0
// Pipeline initialization
HRESULT displayDevice::InitPipeline(ID3D10Blob *VS, ID3D10Blob *PS, ID3D10Blob *PSt, ID3D10Blob *CS)
{
	HRESULT hr = S_OK;
	// Shaders should already be compiled
	if (&pxShader == nullptr || &vxShader == nullptr || &pxShader2 == nullptr || &cpShader == nullptr) return S_FALSE;

	// encapsulate shaders into shader objects
	dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &vxShader);
	dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &pxShader);
	dev->CreatePixelShader(PSt->GetBufferPointer(), PSt->GetBufferSize(), NULL, &pxShader2);
	dev->CreateComputeShader(CS->GetBufferPointer(), CS->GetBufferSize(), NULL, &cpShader);

	// set the shader objects
	devContext->VSSetShader(vxShader, 0, 0);
	devContext->PSSetShader(pxShader, 0, 0);
	devContext->CSSetShader(cpShader, 0, 0);

	// create the input layout
	D3D11_INPUT_ELEMENT_DESC desc[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 }
	};
	dev->CreateInputLayout(desc, 3, VS->GetBufferPointer(), VS->GetBufferSize(), &inputLayout);
	devContext->IASetInputLayout(inputLayout);
	
	// Rasterization stage
	D3D11_RASTERIZER_DESC rd =
	{
		D3D11_FILL_SOLID,	// Fill mode
		D3D11_CULL_NONE,	// Backface culling
		TRUE,				// Culling direction (clockwise or not)
		0,					// Depth Bias (?)
		0,					// Depth bias clamp
		0,					// Slope scaled depth bias
		FALSE,				// Depth clip enable
		FALSE,				// Scissor enable (?)
		FALSE,				// Multisample
		FALSE				// Antialiasing
	};
	ID3D11RasterizerState *rs;
	hr = dev->CreateRasterizerState(&rd, &rs); if (FAILED(hr)) return S_FALSE;
	devContext->RSSetState(rs);
	rs->Release();

	// Depth and Stencil initialization
	hr = InitDepthStencil(); if (FAILED(hr)) return hr;

	return S_OK;
}
예제 #5
0
void TextComponent::DrawTextUI(){

	if (!impl->mModel){
		impl->mModel = gameObject->GetComponent<TextureModelComponent>();
	}

	Game::AddDrawList(DrawStage::UI, [&](){

		if (!impl->mModel)return;
		impl->mModel->SetMatrix();
		Model& model = *impl->mModel->mModel;

		ID3D11DepthStencilState* pBackDS;
		UINT ref;
		Device::mpImmediateContext->OMGetDepthStencilState(&pBackDS, &ref);

		D3D11_DEPTH_STENCIL_DESC descDS = CD3D11_DEPTH_STENCIL_DESC(CD3D11_DEFAULT());
		descDS.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
		//descDS.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
		descDS.DepthFunc = D3D11_COMPARISON_ALWAYS;
		ID3D11DepthStencilState* pDS_tex = NULL;
		Device::mpd3dDevice->CreateDepthStencilState(&descDS, &pDS_tex);
		Device::mpImmediateContext->OMSetDepthStencilState(pDS_tex, 0);

		D3D11_RASTERIZER_DESC descRS = CD3D11_RASTERIZER_DESC(CD3D11_DEFAULT());
		descRS.CullMode = D3D11_CULL_BACK;
		descRS.FillMode = D3D11_FILL_SOLID;

		ID3D11RasterizerState* pRS = NULL;
		Device::mpd3dDevice->CreateRasterizerState(&descRS, &pRS);

		Device::mpImmediateContext->RSSetState(pRS);

		model.Draw(impl->mTexMaterial);

		Device::mpImmediateContext->RSSetState(NULL);
		if (pRS)pRS->Release();

		Device::mpImmediateContext->OMSetDepthStencilState(NULL, 0);
		pDS_tex->Release();

		Device::mpImmediateContext->OMSetDepthStencilState(pBackDS, ref);
		if (pBackDS)pBackDS->Release();
	});
}
예제 #6
0
void HydGraphics::ToggleWireframe()
{
	m_wireframe = !m_wireframe;

	D3D11_RASTERIZER_DESC rs;
	ID3D11RasterizerState * pRasterState;
	HYD3D_pDevContext->RSGetState(&pRasterState);
	pRasterState->GetDesc(&rs);

	if(m_wireframe)
		rs.FillMode = D3D11_FILL_WIREFRAME;
	else
		rs.FillMode = D3D11_FILL_SOLID;

	HYD3D_pDev->CreateRasterizerState( &rs, &pRasterState );
	HYD3D_pDevContext->RSSetState(pRasterState);
	pRasterState->Release();
}
예제 #7
0
void DeferredRendering::Debug_AlbedoOnly_Rendering(RenderTarget* rt){

	Model::mForcedMaterialUseTexture = NULL;

	rt->SetRendererTarget();

	mModelTexture.Update();

	ID3D11DepthStencilState* pBackDS;
	UINT ref;
	Device::mpImmediateContext->OMGetDepthStencilState(&pBackDS, &ref);

	D3D11_DEPTH_STENCIL_DESC descDS = CD3D11_DEPTH_STENCIL_DESC(CD3D11_DEFAULT());
	descDS.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
	descDS.DepthFunc = D3D11_COMPARISON_ALWAYS;
	ID3D11DepthStencilState* pDS_tex = NULL;
	Device::mpd3dDevice->CreateDepthStencilState(&descDS, &pDS_tex);
	Device::mpImmediateContext->OMSetDepthStencilState(pDS_tex, 0);


	D3D11_RASTERIZER_DESC descRS = CD3D11_RASTERIZER_DESC(CD3D11_DEFAULT());
	descRS.CullMode = D3D11_CULL_NONE;
	descRS.FillMode = D3D11_FILL_SOLID;

	ID3D11RasterizerState* pRS = NULL;
	Device::mpd3dDevice->CreateRasterizerState(&descRS, &pRS);

	Device::mpImmediateContext->RSSetState(pRS);

	mModelTexture.Draw(mMaterialDebugDraw);

	Device::mpImmediateContext->RSSetState(NULL);
	if (pRS)pRS->Release();

	Device::mpImmediateContext->OMSetDepthStencilState(NULL, 0);
	pDS_tex->Release();

	Device::mpImmediateContext->OMSetDepthStencilState(pBackDS, ref);
	if (pBackDS)pBackDS->Release();

	RenderTarget::NullSetRendererTarget();
	mMaterialPostEffect.PSSetShaderResources();
}
예제 #8
0
	HRESULT DX11::CreateDeviceD3D (HWND hWnd)
	{
		D3D_FEATURE_LEVEL featureLevel;
		const D3D_FEATURE_LEVEL featureLevelArray[1] = { D3D_FEATURE_LEVEL_11_1 };
		D3D_DRIVER_TYPE md3dDriverType = D3D_DRIVER_TYPE_HARDWARE;
		UINT createDeviceFlags = 0;
#if defined(_DEBUG)
		// If the project is in a debug build, enable the debug layer.
		createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
		createDeviceFlags |= D3D11_CREATE_DEVICE_BGRA_SUPPORT; // enable render on surfaces via d2d
		HRESULT hr = D3D11CreateDevice( nullptr, md3dDriverType, nullptr, createDeviceFlags, nullptr, 0,
				D3D11_SDK_VERSION, &m_pd3dDevice, &featureLevel, &m_pd3dDeviceContext);
		if (hr != S_OK)
		{
			TRACE_MSG(LL_ERROR, CTX_BB | CTX_GFX | CTX_INIT, "D3D11CreateDevice failed, hresult=0x%x", hr);
			return E_FAIL;
		}

		// Setup rasterizer
		{
			D3D11_RASTERIZER_DESC RSDesc;
			memset(&RSDesc, 0, sizeof(D3D11_RASTERIZER_DESC));
			RSDesc.FillMode = D3D11_FILL_SOLID;
			RSDesc.CullMode = D3D11_CULL_NONE;
			RSDesc.FrontCounterClockwise = FALSE;
			RSDesc.DepthBias = 0;
			RSDesc.SlopeScaledDepthBias = 0.0f;
			RSDesc.DepthBiasClamp = 0;
			RSDesc.DepthClipEnable = TRUE;
			RSDesc.ScissorEnable = TRUE;
			RSDesc.AntialiasedLineEnable = FALSE;
			RSDesc.MultisampleEnable = (c_sampleCount > 1) ? TRUE : FALSE;

			ID3D11RasterizerState* pRState = NULL;
			m_pd3dDevice->CreateRasterizerState(&RSDesc, &pRState);
			m_pd3dDeviceContext->RSSetState(pRState);
			pRState->Release();
		}

		return S_OK;
	}
예제 #9
0
void RendererDX11::CreateRasterizerState()
{
    DXGI_SWAP_CHAIN_DESC sd;
    m_d3dSwapChain->GetDesc(&sd);

    // Setup rasterizer state.
    D3D11_RASTERIZER_DESC rasterizerDesc;
    ZeroMemory(&rasterizerDesc, sizeof(D3D11_RASTERIZER_DESC));

    rasterizerDesc.AntialiasedLineEnable = FALSE;
    rasterizerDesc.CullMode = D3D11_CULL_BACK;
    rasterizerDesc.DepthBias = 0;
    rasterizerDesc.DepthBiasClamp = 0.0f;
    rasterizerDesc.DepthClipEnable = TRUE;
    rasterizerDesc.FillMode = D3D11_FILL_SOLID;
    rasterizerDesc.FrontCounterClockwise = FALSE;
    rasterizerDesc.MultisampleEnable = FALSE;
    rasterizerDesc.ScissorEnable = FALSE;
    rasterizerDesc.SlopeScaledDepthBias = 0.0f;

    // Setup rasterizer
    {
        D3D11_RASTERIZER_DESC RSDesc;
        memset(&RSDesc, 0, sizeof(D3D11_RASTERIZER_DESC));
        RSDesc.FillMode = D3D11_FILL_SOLID;
        RSDesc.CullMode = D3D11_CULL_NONE;
        RSDesc.FrontCounterClockwise = FALSE;
        RSDesc.DepthBias = 0;
        RSDesc.SlopeScaledDepthBias = 0.0f;
        RSDesc.DepthBiasClamp = 0;
        RSDesc.DepthClipEnable = TRUE;
        RSDesc.ScissorEnable = TRUE;
        RSDesc.AntialiasedLineEnable = FALSE;
        RSDesc.MultisampleEnable = (sd.SampleDesc.Count > 1) ? TRUE : FALSE;

        ID3D11RasterizerState* pRState = NULL;
        m_d3dDevice->CreateRasterizerState(&RSDesc, &pRState);
        m_d3dDeviceContext->RSSetState(pRState);
        pRState->Release();
    }
}
예제 #10
0
HRESULT InitDeviceD3D(HWND hWnd)
{
    // Setup swap chain
    DXGI_SWAP_CHAIN_DESC sd;
    {
        ZeroMemory(&sd, sizeof(sd));
        sd.BufferCount = 2;
        sd.BufferDesc.Width = 0;
        sd.BufferDesc.Height = 0;
        sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        sd.BufferDesc.RefreshRate.Numerator = 60;
        sd.BufferDesc.RefreshRate.Denominator = 1;
        sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
        sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
        sd.OutputWindow = hWnd;
        sd.SampleDesc.Count = 1;
        sd.SampleDesc.Quality = 0;
        sd.Windowed = TRUE;
        sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    }

    UINT createDeviceFlags = 0;
#ifdef _DEBUG
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
    D3D_FEATURE_LEVEL featureLevel;
    const D3D_FEATURE_LEVEL featureLevelArray[1] = { D3D_FEATURE_LEVEL_11_0, };
    if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 1, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceImmediateContext) != S_OK)
        return E_FAIL;

    // Setup rasterizer
    {
        D3D11_RASTERIZER_DESC RSDesc;
        memset(&RSDesc, 0, sizeof(D3D11_RASTERIZER_DESC));
        RSDesc.FillMode = D3D11_FILL_SOLID;
        RSDesc.CullMode = D3D11_CULL_NONE;
        RSDesc.FrontCounterClockwise = FALSE;
        RSDesc.DepthBias = 0;
        RSDesc.SlopeScaledDepthBias = 0.0f;
        RSDesc.DepthBiasClamp = 0;
        RSDesc.DepthClipEnable = TRUE;
        RSDesc.ScissorEnable = TRUE;
        RSDesc.AntialiasedLineEnable = FALSE;
        RSDesc.MultisampleEnable = (sd.SampleDesc.Count > 1) ? TRUE : FALSE;

        ID3D11RasterizerState* pRState = NULL;
        g_pd3dDevice->CreateRasterizerState(&RSDesc, &pRState);
        g_pd3dDeviceImmediateContext->RSSetState(pRState);
        pRState->Release();
    }

    // Create the render target
    {
        ID3D11Texture2D* pBackBuffer;               
        D3D11_RENDER_TARGET_VIEW_DESC render_target_view_desc;
        ZeroMemory(&render_target_view_desc, sizeof(render_target_view_desc));
        render_target_view_desc.Format = sd.BufferDesc.Format;
        render_target_view_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
        g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
        g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
        g_pd3dDeviceImmediateContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
        pBackBuffer->Release();
    }

    // Create the vertex shader
    {
        static const char* vertexShader = 
            "cbuffer vertexBuffer : register(c0) \
            {\
                float4x4 ProjectionMatrix; \
            };\
            struct VS_INPUT\
            {\
                float2 pos : POSITION;\
                float4 col : COLOR0;\
                float2 uv  : TEXCOORD0;\
            };\
            \
            struct PS_INPUT\
            {\
                float4 pos : SV_POSITION;\
                float4 col : COLOR0;\
                float2 uv  : TEXCOORD0;\
            };\
            \
            PS_INPUT main(VS_INPUT input)\
            {\
                PS_INPUT output;\
                output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
                output.col = input.col;\
                output.uv  = input.uv;\
                return output;\
            }";
예제 #11
0
// Create render states
HRESULT CFW1GlyphRenderStates::createRenderStates(bool anisotropicFiltering) {
	// Create blend-state
	D3D11_BLEND_DESC blendDesc;
	ID3D11BlendState *pBlendState;
	
	ZeroMemory(&blendDesc, sizeof(blendDesc));
	for(int i=0; i < 4; ++i) {
		blendDesc.RenderTarget[i].BlendEnable = TRUE;
		blendDesc.RenderTarget[i].SrcBlend = D3D11_BLEND_ONE;
		blendDesc.RenderTarget[i].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
		blendDesc.RenderTarget[i].BlendOp = D3D11_BLEND_OP_ADD;
		blendDesc.RenderTarget[i].SrcBlendAlpha = D3D11_BLEND_ONE;
		blendDesc.RenderTarget[i].DestBlendAlpha = D3D11_BLEND_ZERO;
		blendDesc.RenderTarget[i].BlendOpAlpha = D3D11_BLEND_OP_ADD;
		blendDesc.RenderTarget[i].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
	}
	
	HRESULT hResult = m_pDevice->CreateBlendState(&blendDesc, &pBlendState);
	if(FAILED(hResult)) {
		m_lastError = L"Failed to create blend state";
	}
	else {
		// Create sampler state
		D3D11_SAMPLER_DESC samplerDesc;
		ID3D11SamplerState *pSamplerState;
		
		ZeroMemory(&samplerDesc, sizeof(samplerDesc));
		if(anisotropicFiltering) {
			samplerDesc.Filter = D3D11_FILTER_ANISOTROPIC;
			samplerDesc.MaxAnisotropy = 2;
			if(m_featureLevel >= D3D_FEATURE_LEVEL_9_2)
				samplerDesc.MaxAnisotropy = 5;
		}
		else
			samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
		samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
		samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
		samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
		samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
		
		hResult = m_pDevice->CreateSamplerState(&samplerDesc, &pSamplerState);
		if(FAILED(hResult)) {
			m_lastError = L"Failed to create sampler state";
		}
		else {
			// Create rasterizer state
			D3D11_RASTERIZER_DESC rasterizerDesc;
			ID3D11RasterizerState *pRasterizerState;
			
			ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));
			rasterizerDesc.FillMode = D3D11_FILL_SOLID;
			rasterizerDesc.CullMode = D3D11_CULL_NONE;
			rasterizerDesc.FrontCounterClockwise = FALSE;
			rasterizerDesc.DepthClipEnable = TRUE;
			
			hResult = m_pDevice->CreateRasterizerState(&rasterizerDesc, &pRasterizerState);
			if(FAILED(hResult)) {
				m_lastError = L"Failed to create rasterizer state";
			}
			else {
				// Create depth-stencil state
				D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
				ID3D11DepthStencilState *pDepthStencilState;
				
				ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
				depthStencilDesc.DepthEnable = FALSE;
				
				hResult = m_pDevice->CreateDepthStencilState(&depthStencilDesc, &pDepthStencilState);
				if(FAILED(hResult)) {
					m_lastError = L"Failed to create depth stencil state";
				}
				else {
					// Success
					m_pBlendState = pBlendState;
					m_pSamplerState = pSamplerState;
					m_pRasterizerState = pRasterizerState;
					m_pDepthStencilState = pDepthStencilState;
					
					hResult = S_OK;
				}
				
				if(FAILED(hResult))
					pRasterizerState->Release();
			}
			
			if(FAILED(hResult))
				pSamplerState->Release();
		}
		
		if(FAILED(hResult))
			pBlendState->Release();
	}
	
	return hResult;
}
예제 #12
0
void D3D11Renderer::ConstructWithWindow(HWND hWnd)
{
	// Create device and swap chain
	DXGI_SWAP_CHAIN_DESC scData;
	ZeroMemory(&scData, sizeof(scData)); // initialize the whole struct to zero

	scData.BufferCount = 1;
	scData.BufferDesc.Width = 1024;
	scData.BufferDesc.Height = 768;
	scData.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	scData.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	scData.BufferDesc.RefreshRate.Numerator = 60;
	scData.BufferDesc.RefreshRate.Denominator = 1;
	scData.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	scData.OutputWindow = hWnd;
	scData.SampleDesc.Count = 1; // MSAA
	scData.Windowed = TRUE;
	scData.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	scData.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	HRESULT hr = D3D11CreateDeviceAndSwapChain(0, D3D_DRIVER_TYPE_HARDWARE, 0, D3D11_CREATE_DEVICE_DEBUG, 0, 0,
		D3D11_SDK_VERSION, &scData, &m_pSwapChain, &m_pD3D11Device, NULL, &m_pD3D11Context);
	assert(hr == S_OK);

	// Create render target view
	ID3D11Texture2D* pBackBuffer;
	m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
	hr = m_pD3D11Device->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); // get buffer through 2D texture
	assert(hr == S_OK);

	// Set the depth resource
	D3D11_TEXTURE2D_DESC depthStencilDesc;
	depthStencilDesc.Width = 1024;
	depthStencilDesc.Height = 768;
	depthStencilDesc.MipLevels = 1;
	depthStencilDesc.ArraySize = 1;
	depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilDesc.SampleDesc.Count = 1;
	depthStencilDesc.SampleDesc.Quality = 0;
	depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
	depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthStencilDesc.CPUAccessFlags = 0;
	depthStencilDesc.MiscFlags = 0;

	D3D11_DEPTH_STENCIL_DESC dsDesc;

	// Depth test parameters
	dsDesc.DepthEnable = false; // true
	dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	dsDesc.DepthFunc = D3D11_COMPARISON_LESS;

	// Stencil test parameters
	dsDesc.StencilEnable = false; // true
	dsDesc.StencilReadMask = 0xFF;
	dsDesc.StencilWriteMask = 0xFF;

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

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

	// Create depth stencil state
	ID3D11DepthStencilState * pDSState;
	m_pD3D11Device->CreateDepthStencilState(&dsDesc, &pDSState);
	m_pD3D11Context->OMSetDepthStencilState(pDSState, 1);

	/*
	D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
	descDSV.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
	descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	descDSV.Texture2D.MipSlice = 0;
	*/

	ID3D11Texture2D* pDepthStencilBuffer;
	m_pD3D11Device->CreateTexture2D(&depthStencilDesc, 0, &pDepthStencilBuffer);
	hr = m_pD3D11Device->CreateDepthStencilView(pDepthStencilBuffer, NULL, &m_pDepthStencilView);
	assert(hr == S_OK);

	// Set rasterizer state
	D3D11_RASTERIZER_DESC rasterizerDesc;
	ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));
	rasterizerDesc.FillMode = D3D11_FILL_SOLID;
	rasterizerDesc.CullMode = D3D11_CULL_NONE;

	ID3D11RasterizerState* pRasterizerState;
	hr = D3D11Renderer::GetInstance()->m_pD3D11Device->CreateRasterizerState(&rasterizerDesc, &pRasterizerState);
	assert(hr == S_OK);
	D3D11Renderer::GetInstance()->m_pD3D11Context->RSSetState(pRasterizerState);

	// Set viewport
	D3D11_VIEWPORT vp;
	ZeroMemory(&vp, sizeof(vp));
	vp.TopLeftX = 0;
	vp.TopLeftY = 0;
	vp.Height = 768;
	vp.Width = 1024;
	vp.MaxDepth = 1.0f;
	m_pD3D11Context->RSSetViewports(1, &vp);

	if (pDepthStencilBuffer)
		pDepthStencilBuffer->Release();
	if (pBackBuffer)
		pBackBuffer->Release();
	if (pRasterizerState)
		pRasterizerState->Release();
}
예제 #13
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdLine, int cmdShow)
{
	DXTInputHandlerDefault inputHandler;
	DXTWindowEventHandlerDefault eventHandler;
	DXTWindow window(hInstance, &inputHandler, &eventHandler);

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

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

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

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

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

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

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

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

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

			window.Present(false);

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

				if (inputHandler.IsKeyDown(VK_ESCAPE))
					break;

				cameraController.Update(deltaTime);

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

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

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

				swapChain->Present(1, 0);
			}

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

		window.Destroy();
	}
}
예제 #14
0
void HydGraphics::InitialiseD3D()
{
	DXGI_SWAP_CHAIN_DESC tSwapDescription;
	ZeroMemory(&tSwapDescription, sizeof(DXGI_SWAP_CHAIN_DESC));

	// fill the swap chain description struct
	tSwapDescription.BufferCount						= 2;      
	tSwapDescription.BufferDesc.Width					= m_width;  
	tSwapDescription.BufferDesc.Height					= m_height;  
	tSwapDescription.BufferDesc.Format					= DXGI_FORMAT_R8G8B8A8_UNORM;     
	tSwapDescription.BufferUsage						= DXGI_USAGE_RENDER_TARGET_OUTPUT;      
	tSwapDescription.OutputWindow						= m_windowHandle;                      
	tSwapDescription.SampleDesc.Count					= 4;                              
	tSwapDescription.SampleDesc.Quality					= 0;   
	tSwapDescription.Windowed							= !m_fullscreen; 
	tSwapDescription.BufferDesc.RefreshRate.Numerator	= 60; 
	tSwapDescription.BufferDesc.RefreshRate.Denominator = 1;
	tSwapDescription.SwapEffect = DXGI_SWAP_EFFECT_SEQUENTIAL   ;
	
	// - Try forcing this all to be SM_3.0 for a while
	D3D_FEATURE_LEVEL tLevel;
	/*D3D_FEATURE_LEVEL aLevels[] = 
	{
		D3D_FEATURE_LEVEL_9_1,
		D3D_FEATURE_LEVEL_9_2,
		D3D_FEATURE_LEVEL_9_3
	};*/
	HRESULT hResult = D3D11CreateDeviceAndSwapChain(NULL,
		D3D_DRIVER_TYPE_HARDWARE,
		NULL,
		D3D11_CREATE_DEVICE_DEBUG,
		NULL,
		NULL,
		D3D11_SDK_VERSION,
		&tSwapDescription,
		&HYD3D_pSwap,
		&HYD3D_pDev,
		&tLevel,
		&HYD3D_pDevContext);


	assert(SUCCEEDED(hResult));

	UINT uNumLevels;
	HYD3D_pDev->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 8, &uNumLevels );

	// Create depth stencil texture
	D3D11_TEXTURE2D_DESC descDepth;
	ZeroMemory( &descDepth, sizeof(descDepth) );

	descDepth.Width					= m_width;
	descDepth.Height				= m_height;
	descDepth.MipLevels				= 1;
	descDepth.ArraySize				= 1;
	descDepth.Format				= DXGI_FORMAT_D24_UNORM_S8_UINT;
	descDepth.SampleDesc.Count		= 4;
	descDepth.SampleDesc.Quality	= 0;
	descDepth.Usage					= D3D11_USAGE_DEFAULT;
	descDepth.BindFlags				= D3D11_BIND_DEPTH_STENCIL;
	descDepth.CPUAccessFlags		= 0;
	descDepth.MiscFlags				= 0;
	
	HRESULT hr = HYD3D_pDev->CreateTexture2D( &descDepth, NULL, &HYD3D_pTexDepthStencil );
	assert(SUCCEEDED(hResult));

	// Create a no-depth state for alternate usage
	D3D11_DEPTH_STENCIL_DESC noDepthDesc;
	ZeroMemory(&noDepthDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));

	noDepthDesc.DepthEnable = false;
	noDepthDesc.StencilEnable = false;

	hr = HYD3D_pDev->CreateDepthStencilState(&noDepthDesc, &HYD3D_pNoDepthStencilState);
	assert(SUCCEEDED(hResult));

	//HYD3D_pDevContext->OMSetDepthStencilState(HYD3D_pNoDepthStencilState, 0);

	// Create the depth stencil view
	D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
	ZeroMemory( &descDSV, sizeof(descDSV) );

	descDSV.Format				= descDepth.Format;
	descDSV.ViewDimension		= D3D11_DSV_DIMENSION_TEXTURE2DMS;
	descDSV.Texture2D.MipSlice	= 0;

	hr = HYD3D_pDev->CreateDepthStencilView( HYD3D_pTexDepthStencil, &descDSV, &HYD3D_pDepthStencilView );
	assert(SUCCEEDED(hResult));

	// Set the viewport
	ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

	viewport.TopLeftX	= 0;
	viewport.TopLeftY	= 0;
	viewport.MinDepth	= 0.0f;
	viewport.MaxDepth	= 1.0f;
	viewport.Width		= (FLOAT)m_width;
	viewport.Height		= (FLOAT)m_height;

	HYD3D_pDevContext->RSSetViewports(1, &viewport);

	ID3D11RasterizerState * pRasterState;

	D3D11_RASTERIZER_DESC rasterizerState;
	rasterizerState.FillMode				= D3D11_FILL_SOLID;
	rasterizerState.CullMode				= D3D11_CULL_NONE;
	rasterizerState.FrontCounterClockwise	= true;
	rasterizerState.DepthBias				= false;
	rasterizerState.DepthBiasClamp			= 0;
	rasterizerState.SlopeScaledDepthBias	= 0;
	rasterizerState.DepthClipEnable			= true;
	rasterizerState.ScissorEnable			= false;
	rasterizerState.MultisampleEnable		= true;
	rasterizerState.AntialiasedLineEnable	= false;

	HYD3D_pDev->CreateRasterizerState( &rasterizerState, &pRasterState );
	HYD3D_pDevContext->RSSetState(pRasterState);
	pRasterState->Release();

	D3D11_BLEND_DESC blendState;
	ZeroMemory(&blendState, sizeof(D3D11_BLEND_DESC));
	blendState.RenderTarget[0].BlendEnable				= TRUE;
	blendState.RenderTarget[0].SrcBlend					= D3D11_BLEND_SRC_ALPHA;
	blendState.RenderTarget[0].DestBlend				= D3D11_BLEND_INV_SRC_ALPHA;
	blendState.RenderTarget[0].BlendOp					= D3D11_BLEND_OP_ADD;
	blendState.RenderTarget[0].SrcBlendAlpha			= D3D11_BLEND_ZERO;
	blendState.RenderTarget[0].DestBlendAlpha			= D3D11_BLEND_ZERO;
	blendState.RenderTarget[0].BlendOpAlpha				= D3D11_BLEND_OP_ADD;
	blendState.RenderTarget[0].RenderTargetWriteMask	= 0x0F;

	HYD3D_pDev->CreateBlendState(&blendState, &HYD3D_pBlendState);
	HYD3D_pDevContext->OMSetBlendState(HYD3D_pBlendState, 0, 0xffffffff);

	// Create a render-target containing the back-buffer
	HYD3D_pSwap->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&HYD3D_tBackBufferTarget.pRenderTarget);
	HYD3D_pDev->CreateRenderTargetView(HYD3D_tBackBufferTarget.pRenderTarget, NULL, &HYD3D_tBackBufferTarget.pRenderTargetView);
	HYD3D_activeRenderTarget = &HYD3D_tBackBufferTarget;

}
예제 #15
0
void ntGenerateTextures(const ShaderScripts& shaderScript, 
                        unsigned int index,
                        nlEngineContext* cxt )
{
    /**/
    ID3D11Device* d3dDevice = cxt->d3dDevice;
    ID3D11DeviceContext* d3dContext = cxt->d3dContext;
    /* シェーダスクリプトの作成 */
    const nlInt8* commonScript = shaderScript.commonScripts.script;
    const nlInt8* tsScript = shaderScript.tsScripts.scripts[index].script;
    nlInt8* combinedScript = (nlInt8*)nlMalloc( nlStrlen(commonScript)+nlStrlen(tsScript)+1);
    nlStrcat( combinedScript, commonScript );
    nlStrcat(combinedScript, tsScript );
    /* シェーダの作成 */
    nlPixelShader texShader = nlCreatePixelShader( combinedScript, nlStrlen( combinedScript ), "main", *cxt );
    nlFree( combinedScript );

    /* 書きこむのに必要なシェーダを作成 */
    nlVertexShader screenVS = nlCreateVertexShader( screenVSScript, nlStrlen( screenVSScript), "vs", *cxt );

    /* テクスチャを作成 */
    nlTexture& tex = cxt->texs[index];
    NL_SAFE_RELEASE( tex.texture );
    NL_SAFE_RELEASE( tex.rtView );
    NL_SAFE_RELEASE( tex.shaderView );
    tex.width  = 512; /* HACK サイズは固定 */
    tex.height = 512; /* HACK サイズは固定 */
    int mipLevel = 1;
    int CPUAccessFlags = 0;
    D3D11_TEXTURE2D_DESC descTarget = 
    {
        tex.width, tex.height,
        mipLevel, 1,
        DXGI_FORMAT_B8G8R8A8_UNORM,
        {1,0}, D3D11_USAGE_DEFAULT,
        (D3D11_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE),
        CPUAccessFlags, 0
    };
    d3dDevice->CreateTexture2D( &descTarget, NULL, &tex.texture );
    d3dDevice->CreateRenderTargetView( tex.texture, NULL, &tex.rtView );
    d3dDevice->CreateShaderResourceView( tex.texture, NULL ,&tex.shaderView );

    /* 現在のRasterStateを取得 */
    ID3D11RasterizerState* oldRasterState;
    d3dContext->RSGetState(&oldRasterState);
    D3D11_RASTERIZER_DESC rasterDesc;
    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;
    ID3D11RasterizerState* rasterState;
    d3dDevice->CreateRasterizerState(&rasterDesc, &rasterState);
    d3dContext->RSSetState(rasterState);
    rasterState->Release();

    /* ビューポートの設定 */
    D3D11_VIEWPORT viewport;
    viewport.Width = tex.width;
    viewport.Height = tex.height;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0.0f;
    viewport.TopLeftY = 0.0f;
    d3dContext->RSSetViewports(1, &viewport);
    /* シェーダを設定する */
    d3dContext->VSSetShader( screenVS.shader_, NULL, 0);
    d3dContext->PSSetShader( texShader.shader_, NULL, 0);
    /* レンダーターゲットを設定する */
    const float clearColor[4] = {0.0f, 0.0f, 1.0f, 0.0f};
    d3dContext->ClearRenderTargetView( tex.rtView, clearColor );
    d3dContext->OMSetRenderTargets( 1, &tex.rtView, NULL );

    /* 全てのテクスチャを設定する */
    /* TODO 毎回全てのテクスチャを設定せずに、このループで設定したテクスチャを省くようにだけする?*/
    for( int i=0;i<((int)index)-1;++i)
    {
        nlTexture& texSamp = cxt->texs[i];
        d3dContext->PSSetShaderResources(i, 1, &texSamp.shaderView );
    }

    /* 描画する */
    d3dContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP );
    d3dContext->Draw( 4, 0 );
    /**/
    d3dContext->VSSetShader( NULL, NULL, 0);
    d3dContext->PSSetShader( NULL, NULL, 0);

    /* ビューポート設定を元に戻す */
    /* 現在のビューポート設定を取得しておく */
    D3D11_VIEWPORT oldViewports = {0.0,0.0,cxt->rendertargets[0].width_,cxt->rendertargets[0].height_,0.0f,1.0f};
    d3dContext->RSSetViewports( 1, &oldViewports );

    /* RasterState設定を元に戻す */
    d3dContext->RSSetState(oldRasterState);
    if( oldRasterState ){ oldRasterState->Release(); }

    /* psの解放 */
    NL_SAFE_RELEASE( screenVS.inputLayout_ );
    NL_SAFE_RELEASE( screenVS.shader_ );
    NL_SAFE_RELEASE( texShader.shader_ );
}
예제 #16
0
파일: CelShadeApp.cpp 프로젝트: endy/Ivy
///////////////////////////////////////////////////////////////////////////////////////////////////
/// CelShadeApp::CelShadeD3D
///
/// @brief
///     Render a cel-shading demo using Direct3D
/// @return
///     N/A
///////////////////////////////////////////////////////////////////////////////////////////////////
void CelShadeApp::CelShadeD3D()
{
    ID3D11DeviceContext* pContext = m_pDxData->pD3D11Context;
    ID3D11Device* pDevice = m_pDxData->pD3D11Device;

    D3DX11_IMAGE_LOAD_INFO imageLoadInfo;
    memset( &imageLoadInfo, 0, sizeof(D3DX11_IMAGE_LOAD_INFO) );
    imageLoadInfo.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    imageLoadInfo.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

    DxTextureCreateInfo shadeTexInfo;
    memset(&shadeTexInfo, 0, sizeof(DxTextureCreateInfo));
    shadeTexInfo.flags.RenderTarget = TRUE;
    shadeTexInfo.flags.ShaderInput = TRUE;
    shadeTexInfo.format = DXGI_FORMAT_R8G8B8A8_UNORM;
    shadeTexInfo.width = m_screenWidth;
    shadeTexInfo.height = m_screenHeight;
    DxTexture* pShadeTex = DxTexture::Create(pDevice, &shadeTexInfo);

    DxTextureCreateInfo edgeTexInfo;
    memset(&edgeTexInfo, 0, sizeof(DxTextureCreateInfo));
    edgeTexInfo.flags.RenderTarget = TRUE;
    edgeTexInfo.flags.ShaderInput = TRUE;
    edgeTexInfo.format = DXGI_FORMAT_R8G8B8A8_UNORM;
    edgeTexInfo.width = m_screenWidth;
    edgeTexInfo.height = m_screenHeight;
    DxTexture* pEdgeTex = DxTexture::Create(pDevice, &edgeTexInfo);

    // Samplers  /////////////////////////////////////////////////////////////////////////////

    // SamplerState PointSampler : register(s0);

    D3D11_SAMPLER_DESC pointSamplerDesc;
    memset(&pointSamplerDesc, 0, sizeof(D3D11_SAMPLER_DESC));
    pointSamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
    pointSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    pointSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    pointSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
    pointSamplerDesc.MinLOD = -FLT_MAX;
    pointSamplerDesc.MaxLOD = FLT_MAX;
    pointSamplerDesc.MipLODBias = 0.0f;
    pointSamplerDesc.MaxAnisotropy = 16;

    ID3D11SamplerState* pPointSampler = NULL;
    pDevice->CreateSamplerState(&pointSamplerDesc, &pPointSampler);

    //
    UINT numVertices = 0, numIndices = 0;
    VertexPTN* pVB = NULL;
    UINT* pIB = NULL;
    ImportPly("Content/dragon_vrip_res3.ply", numVertices, &pVB, numIndices, &pIB);
    //ImportPly("Content/bun_zipper_res4.ply", numVertices, &pVB, numIndices, &pIB);
    DxMeshCreateInfo meshCreateInfo = {0};
    meshCreateInfo.indexCount = numIndices;
    meshCreateInfo.pIndexArray = pIB;
    meshCreateInfo.indexFormat = DXGI_FORMAT_R32_UINT;
    meshCreateInfo.pVertexArray = pVB;
    meshCreateInfo.vertexCount = numVertices;
    meshCreateInfo.vertexElementSize = sizeof(VertexPTN);
    DxMesh* pMesh = DxMesh::Create(pDevice, &meshCreateInfo);

    Plane p;
    DxMeshCreateInfo planeMeshInfo;
    memset(&planeMeshInfo, 0, sizeof(planeMeshInfo));
    planeMeshInfo.pVertexArray = p.GetVB();
    planeMeshInfo.vertexCount = p.NumVertices();
    planeMeshInfo.vertexElementSize = sizeof(VertexPTN);

    DxMesh* pPlaneMesh = DxMesh::Create(pDevice, &planeMeshInfo);

    Cube c;
    DxMeshCreateInfo cubeMeshInfo;
    memset(&cubeMeshInfo, 0, sizeof(cubeMeshInfo));
    cubeMeshInfo.pVertexArray = c.GetVB();
    cubeMeshInfo.vertexCount = c.NumVertices();
    cubeMeshInfo.vertexElementSize = sizeof(VertexPT);

    DxMesh* pCubeMesh = DxMesh::Create(pDevice, &cubeMeshInfo);

    D3D11_SUBRESOURCE_DATA cbInitData;
    memset(&cbInitData, 0, sizeof(D3D11_SUBRESOURCE_DATA));	

    // Camera Buffer
    CameraBufferData cameraData;
    memset(&cameraData, 0, sizeof(CameraBufferData));

    DxBufferCreateInfo cameraBufferCreateInfo = {0};
    cameraBufferCreateInfo.flags.cpuWriteable = TRUE;
    cameraBufferCreateInfo.elemSizeBytes = sizeof(CameraBufferData);
    cameraBufferCreateInfo.pInitialData = &cameraData;
    DxBuffer* pCameraBuffer = DxBuffer::Create(pDevice, &cameraBufferCreateInfo);

    // Shaders ////////////////////////////////////////////////////////////////////////////////////

    m_pPosTexTriVS = DxShader::CreateFromFile(pDevice, "PosTexTri", "Content/shaders/CelShade.hlsl", PosTexVertexDesc, PosTexElements);
    m_pPosTexNormVS = DxShader::CreateFromFile(pDevice, "PosTexNorm", "Content/shaders/CelShade.hlsl", PosTexNormVertexDesc, PosTexNormElements);

    m_pCelShadePS = DxShader::CreateFromFile(pDevice, "CelShade", "Content/shaders/CelShade.hlsl");
    DxShader* pDetectEdges = DxShader::CreateFromFile(pDevice, "DetectEdges", "Content/shaders/CelShade.hlsl");
    DxShader* pApplyTexPS = DxShader::CreateFromFile(pDevice, "ApplyTex", "Content/shaders/CelShade.hlsl");

    DxShader* pCubeVS = DxShader::CreateFromFile(pDevice, "PosTex", "Content/shaders/CelShade.hlsl", PosTexVertexDesc, PosTexElements);
    DxShader* pCubePS = DxShader::CreateFromFile(pDevice, "CubePS", "Content/shaders/CelShade.hlsl");


    ////////////////////////////////////////////////////////////////////////////////////////

    pContext->ClearState();

    // SET RENDER STATE

    FLOAT clearColor[4];
    clearColor[0] = 0.2f;
    clearColor[1] = 0.2f;
    clearColor[2] = 0.2f; 
    clearColor[3] = 1.0f;

    D3D11_RASTERIZER_DESC shadeDesc;
    shadeDesc.FillMode = D3D11_FILL_SOLID;
    shadeDesc.CullMode = D3D11_CULL_BACK;
    shadeDesc.FrontCounterClockwise = FALSE;
    shadeDesc.DepthBias = 0;
    shadeDesc.DepthBiasClamp = 0.0f;
    shadeDesc.SlopeScaledDepthBias = 0;
    shadeDesc.DepthClipEnable = false;
    shadeDesc.ScissorEnable = false;
    shadeDesc.MultisampleEnable = false;
    shadeDesc.AntialiasedLineEnable = false;

    ID3D11RasterizerState* pShadeRS = NULL;
    pDevice->CreateRasterizerState(&shadeDesc, &pShadeRS);

    pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    m_pWindow->Show();

    BOOL quit = false;
    FLOAT yRotationAngle = 0.0f;
    while (!quit)
    {
        ProcessUpdates();

        BeginFrame();

        CameraBufferData* pCameraData = NULL;

        // new frame, clear state
        pContext->ClearState();

        pContext->RSSetViewports(1, &m_pDxData->viewport);
        pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        pContext->RSSetState(pShadeRS);
        pContext->PSSetSamplers(0, 1, &pPointSampler);

        pContext->OMSetRenderTargets(1,
                                       &m_pDxData->pAppRenderTargetView,
                                       m_pDxData->pAppDepthStencilTex->GetDepthStencilView());
        pContext->ClearRenderTargetView(m_pDxData->pAppRenderTargetView, clearColor);
        pContext->ClearDepthStencilView(m_pDxData->pAppDepthStencilTex->GetDepthStencilView(),
                                          D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL,
                                          1.0,
                                          0);

        ///// Draw Mesh ///////////////////////////////////////////////////////////////////////////

        FLOAT viewRotationY = (GetMousePos().x - (m_screenWidth / 2.0f)) /(m_screenWidth / 2.0f);
        viewRotationY *= (3.14159f / 4.0f);

        FLOAT viewRotationZ = (GetMousePos().y - (m_screenHeight / 2.0f)) /(m_screenHeight / 2.0f);
        viewRotationZ *= (3.14159f / 4.0f);

        pCameraData = reinterpret_cast<CameraBufferData*>(pCameraBuffer->Map(pContext));
        pCameraData->worldMatrix = XMMatrixScaling(25, 25, 25) * XMMatrixRotationY(yRotationAngle) *
                                   XMMatrixTranslation(m_pCamera->Position().x,
                                                       m_pCamera->Position().y,
                                                       m_pCamera->Position().z) ;
        // translate world +6 in Z to position camera -9 from world origin
        pCameraData->viewMatrix = m_pCamera->W2C();
        pCameraData->projectionMatrix = m_pCamera->C2S();

        pCameraBuffer->Unmap(pContext);

        pCameraBuffer->BindVS(pContext, 0);

        pMesh->Bind(pContext);

        m_pPosTexNormVS->Bind(pContext);
        m_pCelShadePS->Bind(pContext);
        pMesh->Draw(pContext);

        ///// Detect Edges ///////////////////////////////////////////////////////////////////////////


        ///// Draw Light Position ////////////////////////////////////////////////////////////////////

        //yRotationAngle = 0;
        pCameraData = reinterpret_cast<CameraBufferData*>(pCameraBuffer->Map(pContext));
        pCameraData->worldMatrix = XMMatrixScaling(1, 1, 1);
                                 //  XMMatrixRotationY(yRotationAngle);
                                  // XMMatrixTranslation(-10, 10, 10);
        // translate world +6 in Z to position camera -9 from world origin
        pCameraData->viewMatrix = XMMatrixTranslation(0, 0, 10) * m_pCamera->W2C();
        pCameraData->projectionMatrix = m_pCamera->C2S();

        pCameraBuffer->Unmap(pContext);
        pCameraBuffer->BindVS(pContext, 0);

        pCubeVS->Bind(pContext);

        pCubePS->Bind(pContext);

        pCubeMesh->Bind(pContext);
        pCubeMesh->Draw(pContext);

        ///// Draw UI ////////////////////////////////////////////////////////////////////////////////

        ///@todo Consider moving the following UI drawing to Draw2D()
        m_pUI->Begin();
        // Draw UI stuff
        m_pUI->RenderRect();
        m_pUI->RenderText();
        m_pUI->End();

        /// Blend UI onto final image
        DrawUI();

        m_pDxData->pDXGISwapChain->Present(0,0);

        EndFrame();

        Sleep(50);
        yRotationAngle += 3.14159f / 60.0f;
    }

    // Shader Resource Views

    pCameraBuffer->Destroy();

    // Shaders
    m_pCelShadePS->Destroy();
    m_pCelShadePS = NULL;

    m_pPosTexTriVS->Destroy();
    m_pPosTexTriVS = NULL;

    m_pPosTexNormVS->Destroy();
    m_pPosTexNormVS = NULL;

    pApplyTexPS->Destroy();
    pApplyTexPS = NULL;

    pPlaneMesh->Destroy();
    pPlaneMesh = NULL;

    // Samplers
    pPointSampler->Release();

    // Rasterizer State
    pShadeRS->Release();

    m_pDxData->pD3D11Context->ClearState();
    m_pDxData->pD3D11Context->Flush(); 
}
예제 #17
0
void ntGenerateTextures(const ShaderScripts& shaderScript, 
                        nlEngineContext* cxt )
{
#if 0
    /* この関数が呼ばれる前にテクスチャは解放されている事が期待される */
    for( int i=0;i<MAX_TEXTURE_NUM;++i){ NL_ASSERT( !cxt->texs[i].texture );}
    const ShaderScriptGroup& tsScripts = shaderScript.tsScripts;
    const ShaderScript& commonScrips = shaderScript.commonScripts;
    /**/
    NL_ASSERT( 0 < tsScripts.numScript );
    /**/
    ID3D11Device* d3dDevice = cxt->d3dDevice;
    ID3D11DeviceContext* d3dContext = cxt->d3dContext;

    tsScripts.numScript;
    tsScripts.scripts[0].script;
    tsScripts.scripts[0].name;

    //const nlInt8* script = tsScripts.scripts;
    nlTexture* texuters = &(cxt->texs[0]);
    /**/
    const unsigned int scriptLen = nlStrlen(script);
    /* 全シェーダを作成 */
    ID3D11PixelShader* texturShaders[MAX_TEXTURE_NUM];
    nlMemset( texturShaders, 0, sizeof(ID3D11PixelShader*)*MAX_TEXTURE_NUM );
    /**/
    const unsigned int numTexture = textureScripts.numTexture;
    /**/
    for( unsigned int i=0;i<numTexture;++i)
    {
        ID3DBlob* pBlob = NULL;
        ID3DBlob* pErrorBlob = NULL;
        const nlInt8* funcName = textureScripts.funcs[i];
        const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR;
        /* ピクセルシェーダの作成 */
        if( FAILED(
            D3D10CompileShader(
            script, scriptLen, funcName, shaderMacros, NULL, 
           "main", "ps_4_0",flag, &pBlob, &pErrorBlob ) ) )
        {
            NL_ERR(ERR_009);
            MessageBoxA( NULL, "load texshader error", "", MB_OK );
            if(pErrorBlob)
            {
                NL_ERR(ERR_003, pErrorBlob->GetBufferPointer() );
                MessageBoxA( NULL, (nlInt8*)pErrorBlob->GetBufferPointer(), "", MB_OK );
            }
            return;
        }
        if( pBlob )
        {
            d3dDevice->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &texturShaders[i] );
        }
        ++i;
    }

    /* 書きこむのに必要なシェーダを作成 */
    ID3D11VertexShader* vsRenderQuad;
    ID3DBlob* pBlob = NULL;
    ID3DBlob* pErrorBlob = NULL;    

    NL_HR_ASSSERT( D3D10CompileShader(script, scriptLen, "vs", shaderMacros, NULL, 
        "main","vs_4_0",(D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR),
        &pBlob, &pErrorBlob ) ) ;
    d3dDevice->CreateVertexShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &vsRenderQuad );

    /* 全テクスチャを作成 */
    for(unsigned int i=0;i<numTexture;++i)
    {
        /**/
        nlTexture& tex = texuters[i];
        /**/
        tex.width  = 512; /* HACK サイズは適当 */
        tex.height = 512; /* HACK サイズは適当 */
        int mipLevel = 1;
        int CPUAccessFlags = 0;
        D3D11_TEXTURE2D_DESC descTarget = 
        {
            tex.width, tex.height,
            mipLevel, 1,
            DXGI_FORMAT_B8G8R8A8_UNORM,
            {1,0}, D3D11_USAGE_DEFAULT,
            (D3D11_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE),
            CPUAccessFlags, 0
        };
        d3dDevice->CreateTexture2D( &descTarget, NULL, &tex.texture );
        d3dDevice->CreateRenderTargetView( tex.texture, NULL, &tex.rtView );
        d3dDevice->CreateShaderResourceView( tex.texture, NULL ,&tex.shaderView );
    }

    /* 現在のRasterStateを取得 */
    ID3D11RasterizerState* oldRasterState;
    d3dContext->RSGetState(&oldRasterState);
    /**/
    D3D11_RASTERIZER_DESC rasterDesc;
    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;
    ID3D11RasterizerState* rasterState;
    d3dDevice->CreateRasterizerState(&rasterDesc, &rasterState);
    d3dContext->RSSetState(rasterState);
    rasterState->Release();

    /* 全テクスチャを焼き込む */
    for(unsigned int i=0;i<numTexture;++i)
    {
        /**/
        nlTexture& tex = texuters[i];
        /* ビューポートの設定 */
        D3D11_VIEWPORT viewport;
        viewport.Width = tex.width;
        viewport.Height = tex.height;
        viewport.MinDepth = 0.0f;
        viewport.MaxDepth = 1.0f;
        viewport.TopLeftX = 0.0f;
        viewport.TopLeftY = 0.0f;
        d3dContext->RSSetViewports(1, &viewport);
        /* シェーダを設定する */
        d3dContext->VSSetShader( vsRenderQuad, NULL, 0);
        d3dContext->PSSetShader( texturShaders[i], NULL, 0);
        /* レンダーターゲットを設定する */
        const float clearColor[4] = {0.0f, 0.0f, 1.0f, 0.0f};
        d3dContext->ClearRenderTargetView( tex.rtView, clearColor );
        d3dContext->OMSetRenderTargets( 1, &tex.rtView, NULL );

        /* 全てのテクスチャを設定する */
        /* TODO 毎回全てのテクスチャを設定せずに、このループで設定したテクスチャを省くようにだけする?*/
        for( unsigned int j=0;j<numTexture;++j)
        {
            if( i != j )
            {
                nlTexture& texSamp = texuters[j];
                d3dContext->PSSetShaderResources(j, 1, &texSamp.shaderView );
            }
        }

        /* 描画する */
        d3dContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP );
        d3dContext->Draw( 4, 0 );
    }
    /**/
    d3dContext->VSSetShader( NULL, NULL, 0);
    d3dContext->PSSetShader( NULL, NULL, 0);

    /* ビューポート設定を元に戻す */
    /* 現在のビューポート設定を取得しておく */
    D3D11_VIEWPORT oldViewports = {0.0,0.0,cxt->rendertargets[0].width_,cxt->rendertargets[0].height_,0.0f,1.0f};
    d3dContext->RSSetViewports( 1, &oldViewports );

    /* RasterState設定を元に戻す */
    d3dContext->RSSetState(oldRasterState);
    if( oldRasterState ){ oldRasterState->Release(); }

    /* PSを解放 */
    for(unsigned int i=0;i<numTexture;++i)
    {
        if( texturShaders[i] ){ texturShaders[i]->Release(); }
    }
#endif
}