Exemplo n.º 1
0
void SwapChain11::initPassThroughResources()
{
    ID3D11Device *device = mRenderer->getDevice();

    ASSERT(device != NULL);

    // Make sure our resources are all not allocated, when we create
    ASSERT(mQuadVB == NULL && mPassThroughSampler == NULL);
    ASSERT(mPassThroughIL == NULL && mPassThroughVS == NULL && mPassThroughPS == NULL);

    D3D11_BUFFER_DESC vbDesc;
    vbDesc.ByteWidth = sizeof(d3d11::PositionTexCoordVertex) * 4;
    vbDesc.Usage = D3D11_USAGE_DYNAMIC;
    vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    vbDesc.MiscFlags = 0;
    vbDesc.StructureByteStride = 0;

    HRESULT result = device->CreateBuffer(&vbDesc, NULL, &mQuadVB);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mQuadVB, "Swap chain quad vertex buffer");

    D3D11_SAMPLER_DESC samplerDesc;
    samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 0;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    samplerDesc.BorderColor[0] = 0.0f;
    samplerDesc.BorderColor[1] = 0.0f;
    samplerDesc.BorderColor[2] = 0.0f;
    samplerDesc.BorderColor[3] = 0.0f;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

    result = device->CreateSamplerState(&samplerDesc, &mPassThroughSampler);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mPassThroughSampler, "Swap chain pass through sampler");

    D3D11_INPUT_ELEMENT_DESC quadLayout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    };

    result = device->CreateInputLayout(quadLayout, 2, g_VS_Passthrough, sizeof(g_VS_Passthrough), &mPassThroughIL);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mPassThroughIL, "Swap chain pass through layout");

    result = device->CreateVertexShader(g_VS_Passthrough, sizeof(g_VS_Passthrough), NULL, &mPassThroughVS);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mPassThroughVS, "Swap chain pass through vertex shader");

    result = device->CreatePixelShader(g_PS_PassthroughRGBA, sizeof(g_PS_PassthroughRGBA), NULL, &mPassThroughPS);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mPassThroughPS, "Swap chain pass through pixel shader");
}
Exemplo n.º 2
0
    void init(ID3D11Device& device, Shaders& shaders)
    {
        assert(shaders.mTerrainDS == nullptr);
        assert(shaders.mTerrainVS == nullptr);
        assert(shaders.mTerrainHS == nullptr);
        assert(shaders.mTerrainIL == nullptr);
        assert(shaders.mTerrainPS == nullptr);
        assert(shaders.mTerrainCS == nullptr);

        // Store shader byte code, used to create a shader.
        std::vector<char> shaderByteCode;

        // Vertex shader
        computeShaderByteCode(L"HLSL/TerrainVS.cso", shaderByteCode);
        buildShapesVertexLayout(device, shaderByteCode, shaders.mTerrainIL);
        HRESULT result = device.CreateVertexShader(
            &shaderByteCode[0],
            shaderByteCode.size(),
            nullptr,
            &shaders.mTerrainVS);
        DxErrorChecker(result);

        // Pixel shader
        computeShaderByteCode(L"HLSL/TerrainPS.cso", shaderByteCode);        
        result = device.CreatePixelShader(
            &shaderByteCode[0], 
            shaderByteCode.size(), 
            nullptr, 
            &shaders.mTerrainPS);
        DxErrorChecker(result);

        // Hull shader
        computeShaderByteCode(L"HLSL/TerrainHS.cso", shaderByteCode);        
        result = device.CreateHullShader(
            &shaderByteCode[0], 
            shaderByteCode.size(), 
            nullptr, 
            &shaders.mTerrainHS);
        DxErrorChecker(result);

        // Pixel shader
        computeShaderByteCode(L"HLSL/TerrainDS.cso", shaderByteCode);        
        result = device.CreateDomainShader(
            &shaderByteCode[0], 
            shaderByteCode.size(), 
            nullptr, 
            &shaders.mTerrainDS);
        DxErrorChecker(result);

        // Compute Shader
        computeShaderByteCode(L"HLSL/TerrainCS.cso", shaderByteCode);        
        result = device.CreateComputeShader(
            &shaderByteCode[0], 
            shaderByteCode.size(), 
            nullptr, 
            &shaders.mTerrainCS);
        DxErrorChecker(result);
    }
Exemplo n.º 3
0
	void InitializeShaders()
	{
		D3D11_INPUT_ELEMENT_DESC inputDescription[] =
		{
			{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
			{ "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
		};

		// Load Vertex Shader --------------------------------------
		ID3DBlob* vsBlob;
		D3DReadFileToBlob(L"SampleVertexShader.cso", &vsBlob);

		// Create the shader on the device
		mDevice->CreateVertexShader(
			vsBlob->GetBufferPointer(),
			vsBlob->GetBufferSize(),
			NULL,
			&mVertexShader);

		// Before cleaning up the data, create the input layout
		if (inputDescription) {
			if (mInputLayout != NULL) ReleaseMacro(mInputLayout);
			mDevice->CreateInputLayout(
				inputDescription,					// Reference to Description
				2,									// Number of elments inside of Description
				vsBlob->GetBufferPointer(),
				vsBlob->GetBufferSize(),
				&mInputLayout);
		}

		// Clean up
		vsBlob->Release();

		// Load Pixel Shader ---------------------------------------
		ID3DBlob* psBlob;
		D3DReadFileToBlob(L"SamplePixelShader.cso", &psBlob);

		// Create the shader on the device
		mDevice->CreatePixelShader(
			psBlob->GetBufferPointer(),
			psBlob->GetBufferSize(),
			NULL,
			&mPixelShader);

		// Clean up
		psBlob->Release();

		// Constant buffers ----------------------------------------
		D3D11_BUFFER_DESC cBufferTransformDesc;
		cBufferTransformDesc.ByteWidth = sizeof(mMatrixBuffer);
		cBufferTransformDesc.Usage = D3D11_USAGE_DEFAULT;
		cBufferTransformDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
		cBufferTransformDesc.CPUAccessFlags = 0;
		cBufferTransformDesc.MiscFlags = 0;
		cBufferTransformDesc.StructureByteStride = 0;

		mDevice->CreateBuffer(&cBufferTransformDesc, NULL, &mConstantBuffer);
	}
vpResult vprShaderProgramDX11::init()
{
	vprDeviceDX11* dx11Device = static_cast<vprDeviceDX11*>(m_device);
	ID3D11Device* nativeDevice = dx11Device->getNativeDevice();

	if (m_desc.hasVertexShader())
	{
		if (nativeDevice->CreateVertexShader(m_desc.m_bytecodes[vprShaderStage::VERTEX_SHADER]->getPointer(),
				m_desc.m_bytecodes[vprShaderStage::VERTEX_SHADER]->getSize(), NULL, &m_nativeVertexShader))
		{
			return VP_FAILURE;
		}
	}
	if (m_desc.hasGeometryShader())
	{
		if (nativeDevice->CreateGeometryShader(m_desc.m_bytecodes[vprShaderStage::GEOMETRY_SHADER]->getPointer(),
				m_desc.m_bytecodes[vprShaderStage::GEOMETRY_SHADER]->getSize(), NULL, &m_nativeGeometryShader))
		{
			return VP_FAILURE;
		}
	}
	if (m_desc.hasHullShader())
	{
		if (nativeDevice->CreateHullShader(m_desc.m_bytecodes[vprShaderStage::HULL_SHADER]->getPointer(),
				m_desc.m_bytecodes[vprShaderStage::HULL_SHADER]->getSize(), NULL, &m_nativeHullShader))
		{
			return VP_FAILURE;
		}
	}
	if (m_desc.hasDomainShader())
	{
		if (nativeDevice->CreateDomainShader(m_desc.m_bytecodes[vprShaderStage::DOMAIN_SHADER]->getPointer(),
				m_desc.m_bytecodes[vprShaderStage::DOMAIN_SHADER]->getSize(), NULL, &m_nativeDomainShader))
		{
			return VP_FAILURE;
		}
	}
	if (m_desc.hasPixelShader())
	{
		if (nativeDevice->CreatePixelShader(m_desc.m_bytecodes[vprShaderStage::PIXEL_SHADER]->getPointer(),
				m_desc.m_bytecodes[vprShaderStage::PIXEL_SHADER]->getSize(), NULL, &m_nativePixelShader))
		{
			return VP_FAILURE;
		}
	}
	if (m_desc.hasComputeShader())
	{
		if (nativeDevice->CreateComputeShader(m_desc.m_bytecodes[vprShaderStage::COMPUTE_SHADER]->getPointer(),
				m_desc.m_bytecodes[vprShaderStage::COMPUTE_SHADER]->getSize(), NULL, &m_nativeComputeShader))
		{
			return VP_FAILURE;
		}
	}

	return VP_SUCCESS;
}
Exemplo n.º 5
0
HRESULT CAniShader::Init()
{
	D3D11_INPUT_ELEMENT_DESC tInputLayout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "BONES", 0, DXGI_FORMAT_R32G32B32A32_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "BONES", 1, DXGI_FORMAT_R32G32B32A32_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "WEIGHTS", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "WEIGHTS", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};
	UINT iElementNum = ARRAYSIZE(tInputLayout);


	DWORD swFlag = D3DCOMPILE_ENABLE_STRICTNESS;

#if defined( DEBUG ) || defined( _DEBUG )
	swFlag |= D3D10_SHADER_DEBUG;
#endif

	ID3DBlob* pBlob = NULL, *pErrorBlob = NULL;
	ID3D11Device* pDevice = m_pDevice->GetDevice();

	if (SUCCEEDED(D3DX11CompileFromFile(L"../bin/Data/Fx/VertexAni.fx", NULL, NULL,
		"VS", "vs_4_0", swFlag, 0, NULL, &pBlob, &pErrorBlob, NULL)))
	{
		pDevice->CreateVertexShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &m_pVertexShader);
		pDevice->CreateInputLayout(
			tInputLayout, iElementNum, pBlob->GetBufferPointer(), pBlob->GetBufferSize(), &m_pVertexLayout);
	}
	else
	{
		if (pErrorBlob) { FAILED_CHECK_MSG(E_FAIL, L"셰이더 컴파일 실패"); }
		else { FAILED_CHECK_MSG(E_FAIL, L"셰이더 파일이 존재하지 않습니다."); }
		return E_FAIL;
	}

	pBlob = pErrorBlob = NULL;
	if (SUCCEEDED(D3DX11CompileFromFile(L"../bin/Data/Fx/VertexAni.fx", NULL, NULL,
		"PS", "ps_4_0", swFlag, 0, NULL, &pBlob, &pErrorBlob, NULL)))
	{
		pDevice->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &m_pPixelShader);
	}
	else
	{
		if (pErrorBlob) { FAILED_CHECK_MSG(E_FAIL, L"셰이더 컴파일 실패"); }
		else { FAILED_CHECK_MSG(E_FAIL, L"셰이더 파일이 존재하지 않습니다."); }
		return E_FAIL;
	}
	::Safe_Release(pBlob);
	::Safe_Release(pErrorBlob);

	return S_OK;
}
Exemplo n.º 6
0
	bool H3DVertexShader::Create(const TCHAR* shader_file , const TCHAR* main_func_name , const TCHAR* profile ,
		const D3D11_INPUT_ELEMENT_DESC* input_elem_desc , uint32_t input_elem_num )
	{
		HRESULT result = S_OK;
		ID3D10Blob* err_msg = NULL;
		ID3D10Blob* vscode_buffer = NULL;
		
		// 编译shader代码
		result = D3DX11CompileFromFile( shader_file, NULL, NULL, main_func_name, profile
			, D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, 
			&vscode_buffer, &err_msg, NULL);
		
		if(FAILED(result))
		{
			if(err_msg)
			{
				OutputDebugStringA((char*)(err_msg->GetBufferPointer()));
				OutputDebugStringA("\n");
			}
			else
			{
				OutputDebugString(_T("Missing Shader File\n"));
			}

			H3D_SAFE_RELEASE(err_msg);
			return false;
		}

		void* vscode_buf_pointer = vscode_buffer->GetBufferPointer();
		uint32_t vscode_buf_size = vscode_buffer->GetBufferSize();

		ID3D11Device* device = H3DRenderer::GetSingletonPtr()->GetDevice();
		result = device->CreateVertexShader(
			vscode_buf_pointer, vscode_buf_size, NULL, &vertex_shader_);
		
		if(FAILED(result))
		{
			return false;
		}

		// 创建input layout对象
		result = device->CreateInputLayout( input_elem_desc , input_elem_num , 
			vscode_buf_pointer, vscode_buf_size, &input_layout_);

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

		H3D_SAFE_RELEASE(err_msg);
		H3D_SAFE_RELEASE(vscode_buffer);

		return true;
	}
Exemplo n.º 7
0
	bool Shader::create( GraphicsSystem& graphicsSystem, ShaderType type, const void* pInitData, uint dataSize )
	{
		TIKI_ASSERT( pInitData != nullptr );
		TIKI_ASSERT( dataSize > 0u );

		m_platformData.pShaderCode		= pInitData;
		m_platformData.shaderCodeLength	= dataSize;

		m_type	= type;
		m_hash	= crcBytes( m_platformData.pShaderCode, m_platformData.shaderCodeLength );

		ID3D11Device* pDevice = GraphicsSystemPlatform::getDevice( graphicsSystem );

		HRESULT result = S_FALSE;
		switch ( m_type )
		{
		case ShaderType_ComputeShader:
			result = pDevice->CreateComputeShader( pInitData, dataSize, nullptr, &m_platformData.pComputeShader );
			break;
		case ShaderType_DomainShader:
			result = pDevice->CreateDomainShader( pInitData, dataSize, nullptr, &m_platformData.pDomainShader );
			break;
		case ShaderType_GeometrieShader:
			result = pDevice->CreateGeometryShader( pInitData, dataSize, nullptr, &m_platformData.pGeometryShader );
			break;
		case ShaderType_HullShader:
			result = pDevice->CreateHullShader( pInitData, dataSize, nullptr, &m_platformData.pHullShader );
			break;
		case ShaderType_PixelShader:
			result = pDevice->CreatePixelShader( pInitData, dataSize, nullptr, &m_platformData.pPixelShader );
			break;
		case ShaderType_VertexShader:
			result = pDevice->CreateVertexShader( pInitData, dataSize, nullptr, &m_platformData.pVertexShader );
			break;
		default:
			TIKI_BREAK( "[graphics] ShaderType not supported.\n" );
			break;
		}

		if ( FAILED( result ) || m_platformData.pShaderObject == nullptr )
		{
			dispose( graphicsSystem );
			return false;
		}

		return true;
	}
Exemplo n.º 8
0
bool DX11Shader::Load(const std::string& fxFileName)
{
  ID3D11Device* dd = DX11::GetDevice();

  // Compile the vertex shader
  HRESULT hr = CompileShaderFromFile(fxFileName.c_str(), "VS", "vs_4_0", &m_pVSBlob );
  if (FAILED(hr))
  {
    return false;
  }

	// Create the vertex shader
	hr = dd->CreateVertexShader(m_pVSBlob->GetBufferPointer(), 
    m_pVSBlob->GetBufferSize(), NULL, &m_pVertexShader);
	if (FAILED(hr))
	{	
    ReportError("Failed to create vertex shader for " + fxFileName);
    m_pVSBlob->Release();
    return false;
	}

	// Compile the pixel shader
	ID3DBlob* pPSBlob = NULL;
  hr = CompileShaderFromFile(fxFileName.c_str(), "PS", "ps_4_0", &pPSBlob );
	if (FAILED(hr))  
  {
    ReportError("Failed to compile pixel shader for " + fxFileName);
    return false;
  }

	// Create the pixel shader
	hr = dd->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &m_pPixelShader );
	pPSBlob->Release();
  if (FAILED(hr))
  {
    return false;
    ReportError("Failed to create pixel shader for " + fxFileName);
  }

  return true;
}
Exemplo n.º 9
0
void TerrainShader::InitializeShaders(ID3D11DeviceContext* deviceContext)
{
    // Helper to get device.
    ID3D11Device* device = DX::GetDevice(deviceContext);

    DX::ThrowIfFailed(device->CreateVertexShader(TerrainShaders::TerrainVertexShaderBytecode, sizeof(TerrainShaders::TerrainVertexShaderBytecode), nullptr, vertexShader.GetAddressOf()));
    DX::ThrowIfFailed(device->CreatePixelShader(TerrainShaders::TerrainPixelShaderBytecode, sizeof(TerrainShaders::TerrainPixelShaderBytecode), nullptr, pixelShader.GetAddressOf()));
    DX::ThrowIfFailed(device->CreateInputLayout(DirectX::VertexPositionNormalColorDualTexture::InputElements, DirectX::VertexPositionNormalColorDualTexture::InputElementCount, TerrainShaders::TerrainVertexShaderBytecode, sizeof(TerrainShaders::TerrainVertexShaderBytecode), inputLayout.GetAddressOf()));

    states = std::make_unique<DirectX::CommonStates>(device);

    // Load textures
    DirectX::CreateWICTextureFromFile(device, L"Data/color.png", nullptr, texture0.ReleaseAndGetAddressOf());
    DirectX::CreateDDSTextureFromFile(device, L"Data/base.dds", nullptr, texture1.ReleaseAndGetAddressOf());
    DirectX::CreateWICTextureFromFile(device, L"Data/red.dds", nullptr, texture2.ReleaseAndGetAddressOf());
    DirectX::CreateDDSTextureFromFile(device, L"Data/green.dds", nullptr, texture3.ReleaseAndGetAddressOf());
    DirectX::CreateWICTextureFromFile(device, L"Data/blue.dds", nullptr, texture4.ReleaseAndGetAddressOf());

    constantBuffer.Create(device);
    lightBuffer.Create(device);
}
Exemplo n.º 10
0
	bool init(ID3D11Device* dev, int argc, char** argv)
	{
		this->dev = dev;
		ensure(dev->CreateVertexShader(g_vs, sizeof(g_vs), NULL, &vs));
		ensure(dev->CreateHullShader(g_hs, sizeof(g_hs), NULL, &hs));
		ensure(dev->CreateDomainShader(g_ds, sizeof(g_ds), NULL, &ds));
		ensure(dev->CreatePixelShader(g_ps, sizeof(g_ps), NULL, &ps));
		
		D3D11_INPUT_ELEMENT_DESC elements[1] =
		{
			{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,
			0, D3D11_INPUT_PER_VERTEX_DATA, 0},
		};

		ensure(dev->CreateInputLayout(elements, 1, g_vs, sizeof(g_vs), &layout));

		D3D11_BUFFER_DESC bufferd;
		bufferd.ByteWidth = sizeof(vertex_data);
		bufferd.Usage = D3D11_USAGE_IMMUTABLE;
		bufferd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		bufferd.CPUAccessFlags = 0;
		bufferd.MiscFlags = 0;
		bufferd.StructureByteStride = 0;

		D3D11_SUBRESOURCE_DATA buffersd;
		buffersd.pSysMem = vertex_data;

		ensure(dev->CreateBuffer(&bufferd, &buffersd, &vb));

		D3D11_BUFFER_DESC cbd;
		cbd.ByteWidth = (sizeof(cb_frame_t) + 15) & ~15;
		cbd.Usage = D3D11_USAGE_DYNAMIC;
		cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
		cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		cbd.MiscFlags = 0;
		cbd.StructureByteStride = 0;

		ensure(dev->CreateBuffer(&cbd, NULL, &cb_frame));
		return true;
	}
Exemplo n.º 11
0
bool CD3DVertexShader::CreateInternal()
{
  ID3D11Device* pDevice = g_Windowing.Get3D11Device();

  CLog::Log(LOGDEBUG, __FUNCTION__ " - Create the vertex shader.");

  // Create the vertex shader
  if (FAILED(pDevice->CreateVertexShader(m_VSBuffer->GetBufferPointer(), m_VSBuffer->GetBufferSize(), nullptr, &m_VS)))
  {
    CLog::Log(LOGERROR, __FUNCTION__ " - Failed to Create the vertex shader.");
    SAFE_RELEASE(m_VSBuffer);
    return false;
  }

  CLog::Log(LOGDEBUG, __FUNCTION__ " - create the input layout.");

  if (FAILED(pDevice->CreateInputLayout(m_vertexLayout, m_vertexLayoutSize, m_VSBuffer->GetBufferPointer(), m_VSBuffer->GetBufferSize(), &m_inputLayout)))
  {
    CLog::Log(LOGERROR, __FUNCTION__ " - Failed to create the input layout.");
    return false;
  }

  return true;
}
Exemplo n.º 12
0
void
D3D11hud::Init(int width, int height)
{
    Hud::Init(width, height);

    ID3D11Device *device = NULL;
    _deviceContext->GetDevice(&device);

    // define font texture
    D3D11_TEXTURE2D_DESC texDesc;
    texDesc.Width = FONT_TEXTURE_WIDTH;
    texDesc.Height = FONT_TEXTURE_HEIGHT;
    texDesc.MipLevels = 1;
    texDesc.ArraySize = 1;
    texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    texDesc.SampleDesc.Count = 1;
    texDesc.SampleDesc.Quality = 0;
    texDesc.Usage = D3D11_USAGE_DEFAULT;
    texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    texDesc.CPUAccessFlags = 0;
    texDesc.MiscFlags = 0;

    D3D11_SUBRESOURCE_DATA subData;
    subData.pSysMem = font_image;
    subData.SysMemPitch = FONT_TEXTURE_WIDTH*4;
    subData.SysMemSlicePitch = FONT_TEXTURE_WIDTH*FONT_TEXTURE_HEIGHT*4;
    
    HRESULT hr = device->CreateTexture2D(&texDesc, &subData, &_fontTexture);
    assert(_fontTexture);

    // shader resource view 
    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    ZeroMemory(&srvDesc, sizeof(srvDesc));
    srvDesc.Format = texDesc.Format;
    srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    srvDesc.Texture2D.MostDetailedMip = 0;
    srvDesc.Texture2D.MipLevels = texDesc.MipLevels;
    device->CreateShaderResourceView(_fontTexture, &srvDesc, &_shaderResourceView);
    assert(_shaderResourceView);

    D3D11_SAMPLER_DESC samplerDesc;
    ZeroMemory(&samplerDesc, sizeof(samplerDesc));
    samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    samplerDesc.AddressU = samplerDesc.AddressV = samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.MaxAnisotropy = 1;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
    device->CreateSamplerState(&samplerDesc, &_samplerState);
    assert(_samplerState);

    ID3DBlob* pVSBlob;
    ID3DBlob* pPSBlob;
    pVSBlob = d3d11CompileShader(s_VS, "vs_main", "vs_4_0");
    pPSBlob = d3d11CompileShader(s_PS, "ps_main", "ps_4_0");
    assert(pVSBlob);
    assert(pPSBlob);

    D3D11_INPUT_ELEMENT_DESC inputElementDesc[] = {
        { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT,    0,               0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR",    0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(float)*2, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, sizeof(float)*5, D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };
    device->CreateInputLayout(inputElementDesc, ARRAYSIZE(inputElementDesc),
                              pVSBlob->GetBufferPointer(),
                              pVSBlob->GetBufferSize(),
                              &_inputLayout);
    assert(_inputLayout);

    device->CreateVertexShader(pVSBlob->GetBufferPointer(),
                               pVSBlob->GetBufferSize(),
                               NULL, &_vertexShader);
    assert(_vertexShader);

    device->CreatePixelShader(pPSBlob->GetBufferPointer(),
                              pPSBlob->GetBufferSize(),
                              NULL, &_pixelShader);
    assert(_pixelShader);

    D3D11_RASTERIZER_DESC rasDesc;
    rasDesc.FillMode = D3D11_FILL_SOLID;
    rasDesc.CullMode = D3D11_CULL_NONE;
    rasDesc.FrontCounterClockwise = FALSE;
    rasDesc.DepthBias = 0;
    rasDesc.DepthBiasClamp = 0;
    rasDesc.SlopeScaledDepthBias = 0.0f;
    rasDesc.DepthClipEnable = FALSE;
    rasDesc.ScissorEnable = FALSE;
    rasDesc.MultisampleEnable = FALSE;
    rasDesc.AntialiasedLineEnable = FALSE;
    device->CreateRasterizerState(&rasDesc, &_rasterizerState);
    assert(_rasterizerState);

    // constant buffer 
    D3D11_BUFFER_DESC cbDesc;
    cbDesc.Usage = D3D11_USAGE_DYNAMIC;
    cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    cbDesc.MiscFlags = 0;
    cbDesc.ByteWidth = sizeof(CB_HUD_PROJECTION);

    device->CreateBuffer(&cbDesc, NULL, &_constantBuffer);
    assert(_constantBuffer);
}
Exemplo n.º 13
0
// WinMain
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
	HRESULT hr;


	// ウィンドウクラスを登録
	WNDCLASSEX wcex = {
		sizeof( WNDCLASSEX ),			// cbSize
		CS_HREDRAW | CS_VREDRAW,		// style
		WndProc,						// lpfnWndProc
		0,								// cbClsExtra
		0,								// cbWndExtra
		hInstance,						// hInstance
		NULL,							// hIcon
		NULL,							// hCursor
		( HBRUSH )( COLOR_WINDOW + 1 ),	// hbrBackGround
		NULL,							// lpszMenuName
		g_className,					// lpszClassName
		NULL							// hIconSm
	};
	if ( ! RegisterClassEx( &wcex ) )
	{
		MessageBox( NULL, _T( "失敗: RegisterClassEx()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "RegisterClassEx: ok\n" ) );


	// ウィンドウサイズを計算
	RECT r = { 0, 0, 800, 450 };   // 800x450 (16:9)
	if ( ! AdjustWindowRect( &r, WS_OVERLAPPEDWINDOW, FALSE ) )
	{
		MessageBox( NULL, _T( "失敗: AdjustWindowRect()" ), _T( "エラー" ),  MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "AdjustWindowRect: ok (%d, %d)-(%d, %d)\n" ), r.left, r.top, r.right, r.bottom );


	// ウィンドウ生成
	HWND hWnd;
	hWnd = CreateWindow( g_className,
	                     g_windowName,
	                     WS_OVERLAPPEDWINDOW,
	                     CW_USEDEFAULT,
	                     0,
	                     r.right - r.left,
	                     r.bottom - r.top,
	                     NULL,
	                     NULL,
	                     hInstance,
	                     NULL );
	if ( hWnd == NULL )
	{
		MessageBox( NULL, _T( "失敗: CreateWindow()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "CreateWindow: ok\n" ) );


	// ウィンドウ表示
	ShowWindow(hWnd, nCmdShow);
	dtprintf( _T( "ShowWindow: ok\n" ) );


	// スワップチェイン設定
	DXGI_SWAP_CHAIN_DESC scDesc = {
		{
			1280,									// BufferDesc.Width
			720,									// BufferDesc.Height
			{
				60,									// BufferDesc.RefreshRate.Numerator
				1									// BufferDesc.RefreshRate.Denominator
			},
			DXGI_FORMAT_R16G16B16A16_FLOAT,			// BufferDesc.Format
			DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED,	// BufferDesc.ScanlineOrdering
			DXGI_MODE_SCALING_CENTERED				// BufferDesc.Scaling
		},
		{
			1,										// SampleDesc.Count
			0										// SampleDesc.Quality
		},
		DXGI_USAGE_RENDER_TARGET_OUTPUT,			// BufferUsage
		1,											// BufferCount
		hWnd,										// OutputWindow
		TRUE,										// Windowed
		DXGI_SWAP_EFFECT_DISCARD,					// SwapEffect
		DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH		// Flags
	};

	// Direct3D11 デバイス・デバイスコンテキスト・スワップチェーン生成
	ID3D11Device        * pDevice        = NULL;
	ID3D11DeviceContext * pDeviceContext = NULL;
	IDXGISwapChain      * pSwapChain     = NULL;
	D3D_FEATURE_LEVEL     feature;
	hr = D3D11CreateDeviceAndSwapChain( NULL,
	                                    D3D_DRIVER_TYPE_HARDWARE,
	                                    NULL,
	                                    0,
	                                    NULL,
	                                    0,
	                                    D3D11_SDK_VERSION,
	                                    &scDesc,
	                                    &pSwapChain,
	                                    &pDevice,
	                                    &feature,
	                                    &pDeviceContext );
	if ( FAILED( hr ) )
	{
		MessageBox( NULL, _T( "失敗: D3D11CreateDeviceAndSwapChain()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "D3D11CreateDeviceAndSwapChain: ok (pDevice: 0x%p, pDeviceContext: 0x%p, pSwapChain: 0x%p, feature: 0x%4x)\n" ),
	          pDevice,
	          pDeviceContext,
	          pSwapChain,
	          ( int ) feature );


	// バックバッファテクスチャ取得
	ID3D11Texture2D * pBackBuffer = NULL;
	hr = pSwapChain->GetBuffer( 0, __uuidof( pBackBuffer ), reinterpret_cast< void ** >( &pBackBuffer ) );
	if ( FAILED( hr ) )
	{
		MessageBox( NULL, _T( "失敗: IDXGISwapChain::GetBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "IDXGISwapChain::GetBuffer: ok (pBackBuffer: 0x%p)\n" ), pBackBuffer );


	// レンダーターゲットビュー生成
	ID3D11RenderTargetView * pRenderTargetView = NULL;
	hr = pDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRenderTargetView );
	if ( FAILED( hr ) )
	{
		MessageBox( NULL, _T( "失敗: ID3D11Device::CreateRenderTargetView()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "ID3D11Device::CreateRenderTargetView: ok (pRenderTargetView: 0x%p)\n" ), pRenderTargetView );


	// レンダーターゲットビューをバインド
	pDeviceContext->OMSetRenderTargets( 1, &pRenderTargetView, NULL );
	dtprintf( _T( "ID3D11DeviceContext::OMSetRenderTargets: ok\n" ) );


	// バックバッファはもうここでは使わない
	COM_SAFE_RELEASE( pBackBuffer );


	// ビューポートをバインド
	D3D11_VIEWPORT viewport = {
		   0.0f,		// TopLeftX
		   0.0f,		// TopLeftY
		1280.0f,		// Width
		 720.0f,		// Height
		   0.0f,		// MinDepth
		   1.0f			// MaxDepth
	};
	pDeviceContext->RSSetViewports( 1, &viewport );
	dtprintf( _T( "ID3D11DeviceContext::RSSetViewports: ok\n" ) );


	// 頂点データ
	float vertices[ 5 ][ 7 ] = {
	//    Xaxis  Yaxis  Zaxis  赤     緑     青     Alpha
		{  0.0f,  0.0f,  0.0f,  1.0f,  1.0f,  1.0f,  1.0f },   // 原点
		{ -0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f },   // 左上
		{  0.5f,  0.5f,  0.5f,  1.0f,  1.0f,  0.0f,  1.0f },   // 右上
		{  0.5f, -0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f },   // 右下
		{ -0.5f, -0.5f,  0.5f,  0.0f,  1.0f,  1.0f,  1.0f }    // 左下
	};
	// 入力エレメント記述子
	D3D11_INPUT_ELEMENT_DESC verticesDesc[] = {
		{ "IN_POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,    0, 0,               D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "IN_COLOR",    0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, sizeof(float)*3, D3D11_INPUT_PER_VERTEX_DATA, 0 }
	};

	// 頂点バッファを生成
	D3D11_BUFFER_DESC vertexBufferDesc = {
		5 * sizeof( float ) * 7,	// ByteWidth
		D3D11_USAGE_DEFAULT,		// Usage
		D3D11_BIND_VERTEX_BUFFER,	// BindFlags
		0,							// CPUAccessFlags
		0,							// MiscFlags
		0							// StructureByteStride
	};
	D3D11_SUBRESOURCE_DATA vertexResourceData = { vertices };

	ID3D11Buffer * pVertexBuffer = NULL;
	hr = pDevice->CreateBuffer( &vertexBufferDesc, &vertexResourceData, &pVertexBuffer );
	if ( FAILED( hr ) )
	{
		MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pVertexBuffer: 0x%p)\n" ), pVertexBuffer );

	// 頂点バッファをバインド
	UINT strides[] = { sizeof( float ) * 7 };
	UINT offsets[] = { 0 };
	pDeviceContext->IASetVertexBuffers( 0, 1, &pVertexBuffer, strides, offsets );
	dtprintf( _T( "ID3D11DeviceContext::IASetVertexBuffers: ok\n" ) );


	// インデックスデータ
	unsigned int indices[] = { 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 1 };

	// インデックスバッファを生成
	D3D11_BUFFER_DESC indexBufferDesc = {
		sizeof( unsigned int ) * 12,	// ByteWidth
		D3D11_USAGE_DEFAULT,			// Usage
		D3D11_BIND_INDEX_BUFFER,		// BindFlags
		0,								// CPUAccessFlags
		0,								// MiscFlags
		0								// StructureByteStride
	};
	D3D11_SUBRESOURCE_DATA indexResourceData = { indices };

	ID3D11Buffer * pIndexBuffer = NULL;
	hr = pDevice->CreateBuffer( &indexBufferDesc, &indexResourceData, &pIndexBuffer );
	if ( FAILED( hr ) )
	{
		MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pIndexBuffer: 0x%p)\n" ), pIndexBuffer );

	// インデックスバッファをバインド
	pDeviceContext->IASetIndexBuffer( pIndexBuffer, DXGI_FORMAT_R32_UINT, 0 );
	dtprintf( _T( "ID3D11DeviceContext::IASetIndexBuffer: ok\n" ) );


	// プリミティブタイプを設定
	pDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
	dtprintf( _T( "ID3D11DeviceContext::IASetPrimitiveTopology: ok\n" ) );


	// 頂点シェーダを作成
	ID3D11VertexShader * pVertexShader = NULL;
	hr = pDevice->CreateVertexShader( g_vs_constant, sizeof( g_vs_constant ), NULL, &pVertexShader );
	if ( FAILED( hr ) )
	{
		MessageBox( NULL, _T( "失敗: ID3D11Device::CreateVertexShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "ID3D11Device::CreateVertexShader: ok (pVertexShader: 0x%p)\n" ), pVertexShader );


	// ピクセルシェーダを作成
	ID3D11PixelShader * pPixelShader = NULL;
	hr = pDevice->CreatePixelShader( g_ps_constant, sizeof( g_ps_constant ), NULL, &pPixelShader );
	if ( FAILED( hr ) )
	{
		MessageBox( NULL, _T( "失敗: ID3D11Device::CreatePixelShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "ID3D11Device::CreatePixelShader: ok (pPixelShader: 0x%p)\n" ), pPixelShader );


	// シェーダをバインド
	pDeviceContext->VSSetShader( pVertexShader, NULL, 0 );
	dtprintf( _T( "ID3D11DeviceContext::VSSetShader: ok\n" ) );
	pDeviceContext->PSSetShader( pPixelShader, NULL, 0 );
	dtprintf( _T( "ID3D11DeviceContext::PSSetShader: ok\n" ) );
	pDeviceContext->GSSetShader( NULL, NULL, 0 );
	pDeviceContext->HSSetShader( NULL, NULL, 0 );
	pDeviceContext->DSSetShader( NULL, NULL, 0 );


	// 入力レイアウトを生成
	ID3D11InputLayout * pInputLayout = NULL;
	hr = pDevice->CreateInputLayout( verticesDesc, 2, g_vs_constant, sizeof( g_vs_constant ), &pInputLayout );
	if ( FAILED( hr ) )
	{
		MessageBox( NULL, _T( "失敗: ID3D11Device::CreateInputLayout()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
		return 0;
	}
	dtprintf( _T( "ID3D11Device::CreateInputLayout: ok (pInputLayout: 0x%p)\n" ), pInputLayout );


	// 入力レイアウトをバインド
	pDeviceContext->IASetInputLayout( pInputLayout );
	dtprintf( _T( "ID3D11DeviceContext::IASetInputLayout: ok\n" ) );



	MSG msg;

	while ( 1 )
	{
		// メッセージを取得
		if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
		{
			if ( msg.message == WM_QUIT )
			{
				dtprintf( _T( "PeekMessage: WM_QUIT\n" ) );
				break;
			}
			// メッセージ処理
			DispatchMessage( &msg );
		}
		else
		{
			// レンダーターゲットをクリア
			const float clear[ 4 ] = { 0.0f, 0.0f, 1.0f, 1.0f };	// RGBA
			pDeviceContext->ClearRenderTargetView( pRenderTargetView, clear );

			// 描画
			pDeviceContext->DrawIndexed( 12, 0, 0 );

			pSwapChain->Present( 1, 0 );

			// ちょっとだけ待つ
			Sleep( 5 );
		}
	}



	// シェーダをアンバインド
	pDeviceContext->VSSetShader( NULL, NULL, 0 );
	pDeviceContext->PSSetShader( NULL, NULL, 0 );

	// デバイス・リソース解放
	COM_SAFE_RELEASE( pInputLayout );
	COM_SAFE_RELEASE( pPixelShader );
	COM_SAFE_RELEASE( pVertexShader );
	COM_SAFE_RELEASE( pIndexBuffer );
	COM_SAFE_RELEASE( pVertexBuffer );
	COM_SAFE_RELEASE( pRenderTargetView );
	COM_SAFE_RELEASE( pSwapChain );
	COM_SAFE_RELEASE( pDeviceContext );
	COM_SAFE_RELEASE( pDevice );


	return msg.wParam;
}
Exemplo n.º 14
0
void BaseShader::Initialize(std::string vsFile, std::string psFile)
{
	if (m_bInit)
	{
		LogManager::GetInstance().Warning("You've already initialized this Shader (%p)", this);
		return;
	}

	HRESULT result;
	ID3D10Blob* errorMessage = nullptr;
	ID3D10Blob* vertexShaderBuffer = nullptr;
	ID3D10Blob* pixelShaderBuffer = nullptr;

	ID3D11Device* device = Application::GetInstance().GetGraphicsDevice()->GetDXSystem()->GetDevice();

	result = D3DX11CompileFromFile(vsFile.c_str(), nullptr, nullptr, "main", "vs_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, nullptr, &vertexShaderBuffer, &errorMessage, nullptr);
	if (FAILED(result))
	{
		if (errorMessage)
		{
			LogManager::GetInstance().Trace("[HLSL] %s", (const char*)errorMessage->GetBufferPointer());
		}
		else
		{
			LogManager::GetInstance().Warning("InitializeShader missing shader file (%s)", vsFile);
		}
		return;
	}

	result = D3DX11CompileFromFile(psFile.c_str(), nullptr, nullptr, "main", "ps_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, nullptr, &pixelShaderBuffer, &errorMessage, nullptr);
	if (FAILED(result))
	{
		if (errorMessage)
		{
			LogManager::GetInstance().Trace("[HLSL] %s", (const char*)errorMessage->GetBufferPointer());
		}
		else
		{
			LogManager::GetInstance().Warning("InitializeShader missing shader file (%s)", psFile);
		}
		return;
	}

	result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), nullptr, &m_vertexShader);
	if (FAILED(result))
	{
		LogManager::GetInstance().Error("InitializeShader could not create vertex shader");
		return;
	}

	result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), nullptr, &m_pixelShader);
	if (FAILED(result))
	{
		LogManager::GetInstance().Error("InitializeShader could not create pixel shader");
		return;
	}

	std::vector<D3D11_INPUT_ELEMENT_DESC> polygonLayout;

	ID3D11ShaderReflection* vertexShaderReflection = nullptr;
	ID3D11ShaderReflection* pixelShaderReflection = nullptr;

	result = D3DReflect(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&vertexShaderReflection);
	if (FAILED(result))
	{
		LogManager::GetInstance().Error("BaseShader: Could not peek into the VertexShader");
		return;
	}

	result = D3DReflect(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pixelShaderReflection);
	if (FAILED(result))
	{
		LogManager::GetInstance().Error("BaseShader: Could not peek into the PixelShader");
		return;
	}

	D3D11_SHADER_DESC pixelDesc;
	pixelShaderReflection->GetDesc(&pixelDesc);
	for (unsigned int i = 0; i < pixelDesc.BoundResources; i++)
	{
		D3D11_SHADER_INPUT_BIND_DESC inputDesc;
		pixelShaderReflection->GetResourceBindingDesc(i, &inputDesc);

		//BindCount is the size of the array
		if (inputDesc.Type == D3D_SIT_TEXTURE)
		{
			m_supportedTextures[inputDesc.BindPoint] = true;
		}
	}

	D3D11_SHADER_DESC shaderDesc;
	vertexShaderReflection->GetDesc(&shaderDesc);
	for (unsigned int i = 0; i < shaderDesc.InputParameters; i++)
	{
		D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
		vertexShaderReflection->GetInputParameterDesc(i, &paramDesc);

		D3D11_INPUT_ELEMENT_DESC elementDesc;
		elementDesc.SemanticName = paramDesc.SemanticName;
		elementDesc.SemanticIndex = paramDesc.SemanticIndex;
		elementDesc.InputSlot = 0;
		elementDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
		elementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		elementDesc.InstanceDataStepRate = 0;

		if (paramDesc.Mask == 1)
		{
			switch (paramDesc.ComponentType)
			{
			case D3D_REGISTER_COMPONENT_UINT32:
				elementDesc.Format = DXGI_FORMAT_R32_UINT;
				break;
			case D3D_REGISTER_COMPONENT_SINT32:
				elementDesc.Format = DXGI_FORMAT_R32_SINT;
				break;
			case D3D_REGISTER_COMPONENT_FLOAT32:
				elementDesc.Format = DXGI_FORMAT_R32_FLOAT;
				break;
			default:
				LogManager::GetInstance().Error("Shader: Unknown RegisterComponentType, Mask = 1");
				return;
			}
		}
		else if (paramDesc.Mask <= 3)
		{
			switch (paramDesc.ComponentType)
			{
			case D3D_REGISTER_COMPONENT_UINT32:
				elementDesc.Format = DXGI_FORMAT_R32G32_UINT;
				break;
			case D3D_REGISTER_COMPONENT_SINT32:
				elementDesc.Format = DXGI_FORMAT_R32G32_SINT;
				break;
			case D3D_REGISTER_COMPONENT_FLOAT32:
				elementDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
				break;
			default:
				LogManager::GetInstance().Error("Shader: Unknown RegisterComponentType, Mask <= 3");
				return;
			}
		}
		else if (paramDesc.Mask <= 7)
		{
			switch (paramDesc.ComponentType)
			{
			case D3D_REGISTER_COMPONENT_UINT32:
				elementDesc.Format = DXGI_FORMAT_R32G32B32_UINT;
				break;
			case D3D_REGISTER_COMPONENT_SINT32:
				elementDesc.Format = DXGI_FORMAT_R32G32B32_SINT;
				break;
			case D3D_REGISTER_COMPONENT_FLOAT32:
				elementDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT;
				break;
			default:
				LogManager::GetInstance().Error("Shader: Unknown RegisterComponentType, Mask <= 7");
				return;
			}
		}
		else if (paramDesc.Mask <= 15)
		{
			switch (paramDesc.ComponentType)
			{
			case D3D_REGISTER_COMPONENT_UINT32:
				elementDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT;
				break;
			case D3D_REGISTER_COMPONENT_SINT32:
				elementDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT;
				break;
			case D3D_REGISTER_COMPONENT_FLOAT32:
				elementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
				break;
			default:
				LogManager::GetInstance().Error("Shader: Unknown RegisterComponentType, Mask <= 15");
				return;
			}
		}

		polygonLayout.push_back(elementDesc);
	}

	result = device->CreateInputLayout(&polygonLayout[0], polygonLayout.size(), vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout);
	
	if (FAILED(result))
	{
		LogManager::GetInstance().Error("Shader: Failed to create the input layout");
		return;
	}

	vertexShaderReflection->Release();
	vertexShaderReflection = nullptr;

	pixelShaderReflection->Release();
	pixelShaderReflection = nullptr;

	D3D11_SAMPLER_DESC samplerDesc;

	samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.MipLODBias = 0.0f;
	samplerDesc.MaxAnisotropy = 1;
	samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
	samplerDesc.BorderColor[0] = 0;
	samplerDesc.BorderColor[1] = 0;
	samplerDesc.BorderColor[2] = 0;
	samplerDesc.BorderColor[3] = 0;
	samplerDesc.MinLOD = 0;
	samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

	result = device->CreateSamplerState(&samplerDesc, &m_sampleState);
	if (FAILED(result))
	{
		LogManager::GetInstance().Error("InitializeShader could not create the texture sampler state");
		return;
	}

	m_bInit = true;
}
bool SetupRendering(osvr::renderkit::GraphicsLibrary library) {
    // Make sure our pointers are filled in correctly.
    if (library.D3D11 == nullptr) {
        std::cerr << "SetupRendering: No D3D11 GraphicsLibrary, this should "
                     "not happen"
                  << std::endl;
        return false;
    }

    ID3D11Device* device = library.D3D11->device;
    ID3D11DeviceContext* context = library.D3D11->context;

    // Setup vertex shader
    auto hr = device->CreateVertexShader(g_triangle_vs, sizeof(g_triangle_vs),
                                         nullptr, vertexShader.GetAddressOf());
    if (FAILED(hr)) {
        return false;
    }

    // Setup pixel shader
    hr = device->CreatePixelShader(g_triangle_ps, sizeof(g_triangle_ps),
                                   nullptr, pixelShader.GetAddressOf());
    if (FAILED(hr)) {
        return false;
    }

    // Set the input layout
    ID3D11InputLayout* vertexLayout;
    D3D11_INPUT_ELEMENT_DESC layout[] = {
        {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
         D3D11_INPUT_PER_VERTEX_DATA, 0},
    };
    hr = device->CreateInputLayout(layout, _countof(layout), g_triangle_vs,
                                   sizeof(g_triangle_vs), &vertexLayout);
    if (SUCCEEDED(hr)) {
        context->IASetInputLayout(vertexLayout);
        vertexLayout->Release();
        vertexLayout = nullptr;
    }

    // Create vertex buffer
    SimpleVertex vertices[3];
    vertices[0].Pos.x = 0.0f;
    vertices[0].Pos.y = 0.5f;
    vertices[0].Pos.z = 0.5f;
    vertices[1].Pos.x = 0.5f;
    vertices[1].Pos.y = -0.5f;
    vertices[1].Pos.z = 0.5f;
    vertices[2].Pos.x = -0.5f;
    vertices[2].Pos.y = -0.5f;
    vertices[2].Pos.z = 0.5f;
    CD3D11_BUFFER_DESC bufferDesc(sizeof(SimpleVertex) * _countof(vertices),
                                  D3D11_BIND_VERTEX_BUFFER);
    D3D11_SUBRESOURCE_DATA subResData = {vertices, 0, 0};
    hr = device->CreateBuffer(&bufferDesc, &subResData, &g_vertexBuffer);

    // Describe how depth and stencil tests should be performed.
    // In particular, that they should not be for this 2D example
    // where we want to render a triangle no matter what.
    D3D11_DEPTH_STENCIL_DESC depthStencilDescription = {};
    depthStencilDescription.DepthEnable = false;
    depthStencilDescription.StencilEnable = false;

    // Create depth stencil state and set it.
    hr = device->CreateDepthStencilState(&depthStencilDescription,
                                         &g_depthStencilState);
    if (FAILED(hr)) {
        std::cerr << "SetupRendering: Could not create depth/stencil state"
                  << std::endl;
        return false;
    }

    return true;
}
Exemplo n.º 16
0
bool D11State::init() {
	HRESULT hr;

	ID3D11Texture2D* pBackBuffer = NULL;
	hr = pSwapChain->GetBuffer(0, __uuidof(*pBackBuffer), (LPVOID*)&pBackBuffer);
	if (FAILED(hr)) {
		ods("D3D11: pSwapChain->GetBuffer failure!");
		return false;
	}

	hr = pDevice->CreateDeferredContext(0, &pDeviceContext);
	// Depending on the device settings a deferred context may not be createable
	// for example if it is a SINGLETHREADED device.
	// (See http://msdn.microsoft.com/en-us/library/windows/desktop/ff476505%28v=vs.85%29.aspx)
	// We handle the expected failure and failure fallback in the same way -
	// by trying to use an immediate context.
	if (FAILED(hr) || !pDeviceContext) {
		ods("D3D11: Failed to create DeferredContext (0x%x). Getting ImmediateContext", hr);
		pDevice->GetImmediateContext(&pDeviceContext);
		D11CreateStateBlock(pDeviceContext, &pOrigStateBlock);
		D11CreateStateBlock(pDeviceContext, &pMyStateBlock);

		pOrigStateBlock->Capture();
		bDeferredContext = false;
	} else {
		bDeferredContext = true;
	}

	D3D11_TEXTURE2D_DESC backBufferSurfaceDesc;
	pBackBuffer->GetDesc(&backBufferSurfaceDesc);

	ZeroMemory(&vp, sizeof(vp));
	vp.Width = static_cast<float>(backBufferSurfaceDesc.Width);
	vp.Height = static_cast<float>(backBufferSurfaceDesc.Height);
	vp.MinDepth = 0;
	vp.MaxDepth = 1;
	vp.TopLeftX = 0;
	vp.TopLeftY = 0;
	pDeviceContext->RSSetViewports(1, &vp);

	hr = pDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRTV);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateRenderTargetView failed!");
		return false;
	}

	pDeviceContext->OMSetRenderTargets(1, &pRTV, NULL);

	// Settings for an "over" operation.
	// https://en.wikipedia.org/w/index.php?title=Alpha_compositing&oldid=580659153#Description
	D3D11_BLEND_DESC blend;
	ZeroMemory(&blend, sizeof(blend));
	blend.RenderTarget[0].BlendEnable = TRUE;
	blend.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
	blend.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blend.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blend.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	blend.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
	blend.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blend.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

	pDevice->CreateBlendState(&blend, &pBlendState);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateBlendState failed!");
		return false;
	}

	pDeviceContext->OMSetBlendState(pBlendState, NULL, 0xffffffff);

	hr = pDevice->CreateVertexShader(g_vertex_shader, sizeof(g_vertex_shader), NULL, &pVertexShader);
	if (FAILED(hr)) {
		ods("D3D11: Failed to create vertex shader.");
		return false;
	}

	hr = pDevice->CreatePixelShader(g_pixel_shader, sizeof(g_pixel_shader), NULL, &pPixelShader);
	if (FAILED(hr)) {
		ods("D3D11: Failed to create pixel shader.");
		return false;
	}

	pTexture = NULL;
	pSRView = NULL;

	// Define the input layout
	D3D11_INPUT_ELEMENT_DESC layout[] = {
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};

	hr = pDevice->CreateInputLayout(layout, ARRAY_NUM_ELEMENTS(layout), g_vertex_shader, sizeof(g_vertex_shader), &pVertexLayout);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateInputLayout failure!");
		return false;
	}

	pDeviceContext->IASetInputLayout(pVertexLayout);

	D3D11_BUFFER_DESC bd;
	ZeroMemory(&bd, sizeof(bd));
	bd.Usage = D3D11_USAGE_DYNAMIC;
	bd.ByteWidth = VERTEXBUFFER_SIZE;
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	bd.MiscFlags = 0;

	hr = pDevice->CreateBuffer(&bd, NULL, &pVertexBuffer);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateBuffer failure!");
		return false;
	}

	DWORD indices[] = {
		0,1,3,
		1,2,3,
	};

	ZeroMemory(&bd, sizeof(bd));
	bd.Usage = D3D11_USAGE_IMMUTABLE;
	bd.ByteWidth = sizeof(DWORD) * 6;
	bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	bd.CPUAccessFlags = 0;
	bd.MiscFlags = 0;
	D3D11_SUBRESOURCE_DATA InitData;
	ZeroMemory(&InitData, sizeof(InitData));
	InitData.pSysMem = indices;

	hr = pDevice->CreateBuffer(&bd, &InitData, &pIndexBuffer);
	if (FAILED(hr)) {
		ods("D3D11: pDevice->CreateBuffer failure!");
		return false;
	}

	// Set index buffer
	pDeviceContext->IASetIndexBuffer(pIndexBuffer, DXGI_FORMAT_R32_UINT, 0);

	// Set primitive topology
	pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	if (!bDeferredContext) {
		pMyStateBlock->Capture();
		pOrigStateBlock->Apply();
	}
	pBackBuffer->Release();

	return true;
}
Exemplo n.º 17
0
void DrawCoordinate()
{		
    struct CB
    {
        XMMATRIX mWorldViewProj;
    };

    ID3D11Device*               pDevice = WE::D3DDevice();
    ID3D11DeviceContext*        pImmediateContext = WE::ImmediateContext();

    static ID3D11VertexShader*  g_pVertexShader = NULL;
    static ID3D11PixelShader*	g_pPixelShader = NULL;
    static ID3D11Buffer*        g_pCB = NULL;
    static const char* g_strBuffer =
        "	cbuffer cbPerObject : register( b0 )										\r\n"
        "	{																			\r\n"
        "		matrix      g_mWorldViewProjection  : packoffset( c0 );		            \r\n"
        "	};																			\r\n"
        "																				\r\n"
        "	struct VS_In																\r\n"
        "	{																			\r\n"
        "		uint    id      	: SV_VERTEXID;										\r\n"
        "	};																			\r\n"
        "																				\r\n"
        "	struct VS_Out																\r\n"
        "	{																			\r\n"
        "		float4 pos			: SV_POSITION;										\r\n"
        "		float4 color        : COLOR;											\r\n"
        "	};																			\r\n"
        "																				\r\n"
        "																				\r\n"
        "	cbuffer cbImmutable															\r\n"
        "	{																			\r\n"
        "		static float4 g_positions[6] =											\r\n"
        "		{																		\r\n"
        "			float4( 0.0f, 0.0f, 0.0f, 1.0f ),									\r\n"
        "			float4( 1.0f, 0.0f, 0.0f, 1.0f ),									\r\n"
        "			float4( 0.0f, 0.0f, 0.0f, 1.0f ),									\r\n"
        "			float4( 0.0f, 1.0f, 0.0f, 1.0f ),									\r\n"
        "			float4( 0.0f, 0.0f, 0.0f, 1.0f ),									\r\n"
        "			float4( 0.0f, 0.0f, 1.0f, 1.0f ),        							\r\n"
        "		};																		\r\n"
        "																				\r\n"
        "		static float4 g_colors[6] =												\r\n"
        "		{																		\r\n"
        "			float4( 1.0f, 0.0f, 0.0f, 1.0f ),									\r\n"
        "			float4( 1.0f, 0.0f, 0.0f, 1.0f ),									\r\n"
        "			float4( 0.0f, 1.0f, 0.0f, 1.0f ),									\r\n"
        "			float4( 0.0f, 1.0f, 0.0f, 1.0f ),									\r\n"
        "			float4( 0.0f, 0.0f, 1.0f, 1.0f ),									\r\n"
        "			float4( 0.0f, 0.0f, 1.0f, 1.0f ),        							\r\n"
        "		};																		\r\n"
        "	};																			\r\n"
        "	VS_Out VSMain(VS_In input)													\r\n"
        "	{																			\r\n"
        "		VS_Out output;															\r\n"
        "																				\r\n"
        "		output.pos = mul( g_positions[input.id] * 5, g_mWorldViewProjection );	\r\n"
        "		output.color = g_colors[input.id];										\r\n"
        "		return output;															\r\n"
        "	}																			\r\n"
        "																	    		\r\n"
        "	float4 PSMain(VS_Out input) : SV_Target							            \r\n"
        "	{   																		\r\n"
        "		return input.color;														\r\n"
        "		return float4( 1.0f, 1.0f, 0.0f, 1.0f );								\r\n"
        "	}																			\r\n"
        "";

    HRESULT hr;

    if ( g_pVertexShader == NULL )
    {
        // Create shaders
        ID3DBlob* pVSBlob = NULL;
        ID3DBlob* pPSBlob = NULL;

        UINT dwBufferSize = ( UINT )strlen( g_strBuffer ) + 1;
        V( WE::CompileShaderFromMemory( g_strBuffer, dwBufferSize, NULL, "VSMain", "vs_5_0", &pVSBlob ) );
        V( WE::CompileShaderFromMemory( g_strBuffer, dwBufferSize, NULL, "PSMain", "ps_5_0", &pPSBlob ) );

        V( pDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader ) );
        V( pDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShader ) );

        SAFE_RELEASE( pVSBlob );
        SAFE_RELEASE( pPSBlob );

        // Create the constant buffers
        D3D11_BUFFER_DESC Desc;
        Desc.Usage = D3D11_USAGE_DYNAMIC;
        Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
        Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
        Desc.MiscFlags = 0;
        Desc.ByteWidth = sizeof( CB );
        V( pDevice->CreateBuffer( &Desc, NULL, &g_pCB ) );
    }

    D3D11_MAPPED_SUBRESOURCE MappedResource;
    V(pImmediateContext->Map( g_pCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
    CB* pPerFrame = ( CB* )MappedResource.pData;
    pPerFrame->mWorldViewProj = XMMatrixTranspose( WE::Camera()->GetViewProjMtx() );
    pImmediateContext->Unmap( g_pCB, 0 );
    pImmediateContext->VSSetConstantBuffers( 0, 1, &g_pCB );

    pImmediateContext->OMSetDepthStencilState( NULL, 0 );
    float vBlendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
    pImmediateContext->OMSetBlendState( NULL, vBlendFactor, 0xFFFFFFFF );
    pImmediateContext->RSSetState( NULL );

    pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINELIST );

    pImmediateContext->VSSetShader( g_pVertexShader, NULL, 0 );
    pImmediateContext->PSSetShader( g_pPixelShader, NULL, 0 );
    pImmediateContext->GSSetShader( NULL, NULL, 0 );

    // Draw
    pImmediateContext->Draw( 6, 0 );
}
Exemplo n.º 18
0
    bool init(ID3D11Device* dev, int argc, char** argv)
    {
        this->dev = dev;

        for(char** p = argv + 1; *p; ++p) {
            if(!strcmp(*p, "-w"))
                wireframe = 1;
            else if(!strcmp(*p, "-b"))
                blue_only = true;
            else if(!strcmp(*p, "-t"))
                triangles = atoi(*++p);
            else if(!strcmp(*p, "-m"))
                impressions = (float)atof(*++p);
            else if(!strcmp(*p, "-p"))
                period = (float)atof(*++p);
            else if(!strcmp(*p, "-s"))
                speed = (float)atof(*++p);
            else {
                fprintf(stderr, "Usage: d3d11gears [-v|-w] [-t TRIANGLES]\n");
                fprintf(stderr, "d3d11gears is an enhanced port of glxgears to Direct3D 11\n");
                fprintf(stderr, "\n");
                //fprintf(stderr, "-v\t\tuse per-vertex diffuse-only lighting (classic glxgears look)\n");
                fprintf(stderr, "-w\t\twireframe mode\n");
                fprintf(stderr, "-t TRIANGLES\ttriangle budget (default is 3200)\n");
                fprintf(stderr, "-m IMPRESSIONS\tmotion blur impressions (default is 1)\n");
                fprintf(stderr, "-p PERIOD\tspeed reversal period (default is infinite)\n");
                fprintf(stderr, "-s SPEED\tgear speed (default is 1.0)\n");
                fprintf(stderr, "-b\tonly show blue gear (for faster motion blur)\n");
                return false;
            }
        }

        ensure(dev->CreatePixelShader(g_ps, sizeof(g_ps), NULL, &ps));
        ensure(dev->CreateVertexShader(g_vs, sizeof(g_vs), NULL, &vs));

        gears[0].color = vec(0.8f, 0.1f, 0.0f, 1.0f);
        gears[1].color = vec(0.0f, 0.8f, 0.2f, 1.0f);
        gears[2].color = vec(0.2f, 0.2f, 1.0f, 1.0f);

        gears[0].mesh = build_gear(dev, triangles / 2, 1.0f, 4.0f, 1.0f, 20, 0.7f);
        gears[1].mesh = build_gear(dev, triangles / 4, 0.5f, 2.0f, 2.0f, 10, 0.7f);
        gears[2].mesh = build_gear(dev, triangles / 4, 1.3f, 2.0f, 0.5f, 10, 0.7f);

        gears[0].x = -3.0f;
        gears[0].y = -2.0f;
        gears[0].wmul = 1.0f;
        gears[0].t0 = 0.0 * M_PI / 180.0f;

        gears[1].x = 3.1f;
        gears[1].y = -2.0f;
        gears[1].wmul = -2.0f;
        gears[1].t0 = -9.0f * (float)M_PI / 180.0f;

        gears[2].x = -3.1f;
        gears[2].y = 4.2f;
        gears[2].wmul = -2.0f;
        gears[2].t0 = -25.0f * (float)M_PI / 180.0f;

        D3D11_BUFFER_DESC bufferd;
        memset(&bufferd, 0, sizeof(bufferd));
        bufferd.ByteWidth = sizeof(cbuf_t);
        bufferd.Usage = D3D11_USAGE_DEFAULT;
        bufferd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
        ensure(dev->CreateBuffer(&bufferd, 0, &cb));

        if(impressions > 1)
        {
            D3D11_BLEND_DESC blendd;
            memset(&blendd, 0, sizeof(blendd));
            blendd.RenderTarget[0].BlendEnable = TRUE;
            blendd.RenderTarget[0].BlendOp = blendd.RenderTarget[0].BlendOpAlpha
                                             = D3D11_BLEND_OP_ADD;
            blendd.RenderTarget[0].SrcBlend = blendd.RenderTarget[0].SrcBlendAlpha
                                              = D3D11_BLEND_BLEND_FACTOR;
            blendd.RenderTarget[0].DestBlend = blendd.RenderTarget[0].DestBlendAlpha
                                               = D3D11_BLEND_ONE;
            blendd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
            ensure(dev->CreateBlendState(&blendd, &blend));

            D3D11_DEPTH_STENCIL_DESC zsad;
            memset(&zsad, 0, sizeof(zsad));
            zsad.DepthEnable = TRUE;
            zsad.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
            zsad.DepthFunc = D3D11_COMPARISON_EQUAL;
            ensure(dev->CreateDepthStencilState(&zsad, &zsa));

            blitter = new d3d11_blitter(dev);
        }

        return true;
    }
Exemplo n.º 19
0
void SwapChain11::initPassThroughResources()
{
    if (mPassThroughResourcesInit)
    {
        return;
    }

    TRACE_EVENT0("gpu.angle", "SwapChain11::initPassThroughResources");
    ID3D11Device *device = mRenderer->getDevice();

    ASSERT(device != NULL);

    // Make sure our resources are all not allocated, when we create
    ASSERT(mQuadVB == NULL && mPassThroughSampler == NULL);
    ASSERT(mPassThroughIL == NULL && mPassThroughVS == NULL && mPassThroughPS == NULL);

    D3D11_BUFFER_DESC vbDesc;
    vbDesc.ByteWidth = sizeof(d3d11::PositionTexCoordVertex) * 4;
    vbDesc.Usage = D3D11_USAGE_DYNAMIC;
    vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    vbDesc.MiscFlags = 0;
    vbDesc.StructureByteStride = 0;

    HRESULT result = device->CreateBuffer(&vbDesc, NULL, &mQuadVB);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mQuadVB, "Swap chain quad vertex buffer");

    D3D11_SAMPLER_DESC samplerDesc;
    samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 0;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    samplerDesc.BorderColor[0] = 0.0f;
    samplerDesc.BorderColor[1] = 0.0f;
    samplerDesc.BorderColor[2] = 0.0f;
    samplerDesc.BorderColor[3] = 0.0f;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

    result = device->CreateSamplerState(&samplerDesc, &mPassThroughSampler);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mPassThroughSampler, "Swap chain pass through sampler");

    D3D11_INPUT_ELEMENT_DESC quadLayout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    };

    result = device->CreateInputLayout(quadLayout, 2, g_VS_Passthrough2D, sizeof(g_VS_Passthrough2D), &mPassThroughIL);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mPassThroughIL, "Swap chain pass through layout");

    result = device->CreateVertexShader(g_VS_Passthrough2D, sizeof(g_VS_Passthrough2D), NULL, &mPassThroughVS);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mPassThroughVS, "Swap chain pass through vertex shader");

    result = device->CreatePixelShader(g_PS_PassthroughRGBA2D, sizeof(g_PS_PassthroughRGBA2D), NULL, &mPassThroughPS);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mPassThroughPS, "Swap chain pass through pixel shader");

    // Use the default rasterizer state but without culling
    D3D11_RASTERIZER_DESC rasterizerDesc;
    rasterizerDesc.FillMode              = D3D11_FILL_SOLID;
    rasterizerDesc.CullMode              = D3D11_CULL_NONE;
    rasterizerDesc.FrontCounterClockwise = FALSE;
    rasterizerDesc.DepthBias             = 0;
    rasterizerDesc.SlopeScaledDepthBias  = 0.0f;
    rasterizerDesc.DepthBiasClamp        = 0.0f;
    rasterizerDesc.DepthClipEnable       = TRUE;
    rasterizerDesc.ScissorEnable         = FALSE;
    rasterizerDesc.MultisampleEnable     = FALSE;
    rasterizerDesc.AntialiasedLineEnable = FALSE;
    result = device->CreateRasterizerState(&rasterizerDesc, &mPassThroughRS);
    ASSERT(SUCCEEDED(result));
    d3d11::SetDebugName(mPassThroughRS, "Swap chain pass through rasterizer state");

    mPassThroughResourcesInit = true;
}
    void CFullscreenTriangleDrawer::CreateDX11Resources()
    {
        ID3D11Device* pDevice = static_cast<ID3D11Device*>( gD3DDevice );

        HRESULT hr = S_OK;

        /*
        // fxc /O2 /T vs_4_0 /E VSMain

        struct VSScreenQuadOutput
        {
            float4 Position : SV_POSITION;
            float2 TexCoords0 : TEXCOORD0;
        };

        VSScreenQuadOutput VSMain(uint VertexID: SV_VertexID)
        {
            VSScreenQuadOutput output = (VSScreenQuadOutput)0;

            output.TexCoords0 = float2( (VertexID << 1) & 2, VertexID & 2 );
            output.Position = float4( output.TexCoords0 * float2( 2.0f, -2.0f ) + float2( -1.0f, 1.0f), 0.0f, 1.0f );

            return output;
        }

        */
        const char CompiledVS[] =
        {
            0x44, 0x58, 0x42, 0x43, 0x0d, 0x62, 0xaf, 0x9b, 0xa7, 0xca, 0xdb, 0xb0,
            0xc3, 0x92, 0xc3, 0xc1, 0x99, 0xd5, 0x59, 0xe6, 0x01, 0x00, 0x00, 0x00,
            0xb4, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
            0x8c, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00,
            0x38, 0x02, 0x00, 0x00, 0x52, 0x44, 0x45, 0x46, 0x50, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x1c, 0x00, 0x00, 0x00, 0x00, 0x04, 0xfe, 0xff, 0x00, 0xc1, 0x00, 0x00,
            0x1c, 0x00, 0x00, 0x00, 0x4d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66,
            0x74, 0x20, 0x28, 0x52, 0x29, 0x20, 0x48, 0x4c, 0x53, 0x4c, 0x20, 0x53,
            0x68, 0x61, 0x64, 0x65, 0x72, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x69, 0x6c,
            0x65, 0x72, 0x20, 0x39, 0x2e, 0x32, 0x39, 0x2e, 0x39, 0x35, 0x32, 0x2e,
            0x33, 0x31, 0x31, 0x31, 0x00, 0xab, 0xab, 0xab, 0x49, 0x53, 0x47, 0x4e,
            0x2c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
            0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00,
            0x53, 0x56, 0x5f, 0x56, 0x65, 0x72, 0x74, 0x65, 0x78, 0x49, 0x44, 0x00,
            0x4f, 0x53, 0x47, 0x4e, 0x50, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
            0x08, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x0f, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
            0x03, 0x0c, 0x00, 0x00, 0x53, 0x56, 0x5f, 0x50, 0x4f, 0x53, 0x49, 0x54,
            0x49, 0x4f, 0x4e, 0x00, 0x54, 0x45, 0x58, 0x43, 0x4f, 0x4f, 0x52, 0x44,
            0x00, 0xab, 0xab, 0xab, 0x53, 0x48, 0x44, 0x52, 0x18, 0x01, 0x00, 0x00,
            0x40, 0x00, 0x01, 0x00, 0x46, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x04,
            0x12, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
            0x67, 0x00, 0x00, 0x04, 0xf2, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x01, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x03, 0x32, 0x20, 0x10, 0x00,
            0x01, 0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00,
            0x29, 0x00, 0x00, 0x07, 0x12, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x0a, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00,
            0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x07, 0x12, 0x00, 0x10, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x01, 0x40, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x07,
            0x42, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x10, 0x10, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
            0x56, 0x00, 0x00, 0x05, 0x32, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x86, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0f,
            0x32, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x10, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
            0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x80, 0xbf, 0x00, 0x00, 0x80, 0x3f,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x05,
            0x32, 0x20, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x46, 0x00, 0x10, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x08, 0xc2, 0x20, 0x10, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f,
            0x3e, 0x00, 0x00, 0x01, 0x53, 0x54, 0x41, 0x54, 0x74, 0x00, 0x00, 0x00,
            0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
            0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        };

        hr = pDevice->CreateVertexShader( CompiledVS, sizeof( CompiledVS ), NULL, &m_pVertexShader11 );
        CRY_ASSERT( SUCCEEDED( hr ) );

        /*
        // fxc /O2 /T ps_4_0 /E PSMain

        Texture2D txDiffuse : register(t0);
        SamplerState texSampler : register(s0);

        struct VSScreenQuadOutput
        {
            float4 Position : SV_POSITION;
            float2 TexCoords0 : TEXCOORD0;
        };

        float4 PSMain(VSScreenQuadOutput input) : SV_Target
        {
            // Switch the red and blue channels for DX11 since CryEngine does
            // not provide the exact texture format required by Coherent UI
            return txDiffuse.Sample(texSampler, input.TexCoords0).bgra;
        }
        */
        const char CompiledPS[] =
        {
            0x44, 0x58, 0x42, 0x43, 0x2a, 0xce, 0xec, 0x64, 0xe0, 0xa8, 0xf3, 0xcd,
            0xc7, 0x9e, 0x5d, 0xcb, 0x86, 0xb6, 0x78, 0x94, 0x01, 0x00, 0x00, 0x00,
            0x70, 0x02, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
            0xe0, 0x00, 0x00, 0x00, 0x38, 0x01, 0x00, 0x00, 0x6c, 0x01, 0x00, 0x00,
            0xf4, 0x01, 0x00, 0x00, 0x52, 0x44, 0x45, 0x46, 0xa4, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
            0x1c, 0x00, 0x00, 0x00, 0x00, 0x04, 0xff, 0xff, 0x00, 0xc1, 0x00, 0x00,
            0x71, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
            0x67, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
            0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
            0x01, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x53,
            0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x00, 0x74, 0x78, 0x44, 0x69, 0x66,
            0x66, 0x75, 0x73, 0x65, 0x00, 0x4d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f,
            0x66, 0x74, 0x20, 0x28, 0x52, 0x29, 0x20, 0x48, 0x4c, 0x53, 0x4c, 0x20,
            0x53, 0x68, 0x61, 0x64, 0x65, 0x72, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x69,
            0x6c, 0x65, 0x72, 0x20, 0x36, 0x2e, 0x33, 0x2e, 0x39, 0x36, 0x30, 0x30,
            0x2e, 0x31, 0x36, 0x33, 0x38, 0x34, 0x00, 0xab, 0x49, 0x53, 0x47, 0x4e,
            0x50, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
            0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
            0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00,
            0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00,
            0x53, 0x56, 0x5f, 0x50, 0x4f, 0x53, 0x49, 0x54, 0x49, 0x4f, 0x4e, 0x00,
            0x54, 0x45, 0x58, 0x43, 0x4f, 0x4f, 0x52, 0x44, 0x00, 0xab, 0xab, 0xab,
            0x4f, 0x53, 0x47, 0x4e, 0x2c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
            0x08, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x0f, 0x00, 0x00, 0x00, 0x53, 0x56, 0x5f, 0x54, 0x61, 0x72, 0x67, 0x65,
            0x74, 0x00, 0xab, 0xab, 0x53, 0x48, 0x44, 0x52, 0x80, 0x00, 0x00, 0x00,
            0x40, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x03,
            0x00, 0x60, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x18, 0x00, 0x04,
            0x00, 0x70, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x55, 0x00, 0x00,
            0x62, 0x10, 0x00, 0x03, 0x32, 0x10, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00,
            0x65, 0x00, 0x00, 0x03, 0xf2, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x68, 0x00, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x09,
            0xf2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x10, 0x10, 0x00,
            0x01, 0x00, 0x00, 0x00, 0x46, 0x7e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x60, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x05,
            0xf2, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x0c, 0x10, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x01, 0x53, 0x54, 0x41, 0x54,
            0x74, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        };

        hr = pDevice->CreatePixelShader( CompiledPS, sizeof( CompiledPS ), NULL, &m_pPixelShader11 );
        CRY_ASSERT( SUCCEEDED( hr ) );

        // Create a One/InvSrcAlpha blend state
        D3D11_BLEND_DESC blendDesc = { 0 };
        blendDesc.AlphaToCoverageEnable  = false;
        blendDesc.IndependentBlendEnable = false;

        blendDesc.RenderTarget[0].BlendEnable			 = true;
        blendDesc.RenderTarget[0].BlendOp				 = D3D11_BLEND_OP_ADD;
        blendDesc.RenderTarget[0].BlendOpAlpha			 = D3D11_BLEND_OP_ADD;
        blendDesc.RenderTarget[0].DestBlend			     = D3D11_BLEND_INV_SRC_ALPHA;
        blendDesc.RenderTarget[0].DestBlendAlpha		 = D3D11_BLEND_ONE;
        blendDesc.RenderTarget[0].RenderTargetWriteMask  = D3D11_COLOR_WRITE_ENABLE_ALL;
        blendDesc.RenderTarget[0].SrcBlend				 = D3D11_BLEND_ONE;
        blendDesc.RenderTarget[0].SrcBlendAlpha		     = D3D11_BLEND_ONE;

        hr = pDevice->CreateBlendState( &blendDesc, &m_pBlendState11 );
        CRY_ASSERT( SUCCEEDED( hr ) );
    }
Exemplo n.º 21
0
void FMaterial::Compile(const FShaderProgramInfo* VertexShaderInfo, const FShaderProgramInfo* PixelShaderInfo, const FShaderProgramInfo* GeometryShaderInfo, const FShaderProgramInfo* HullShaderInfo, const FShaderProgramInfo* DomainShaderInfo)
{
	ID3D11Device* Device = GraphicsContext->GetDevice();

	// Core shaders blobs
	FBlobPointer VertexShaderBlob, PixelShaderBlob;

	// Optional shaders blobs
	FBlobPointer GeometryShaderBlob, HullShaderBlob, DomainShaderBlob;

	bool bCompilationSuccessful = VertexShaderInfo->Compile(VertexShaderBlob.GetReference()) && PixelShaderInfo->Compile(PixelShaderBlob.GetReference());

	if (GeometryShaderInfo != nullptr)
	{
		GeometryShaderInfo->Compile(GeometryShaderBlob.GetReference());
	}

	if (DomainShaderInfo != nullptr && HullShaderInfo != nullptr)
	{
		DomainShaderInfo->Compile(DomainShaderBlob.GetReference());
		HullShaderInfo->Compile(HullShaderBlob.GetReference());
	}

	if (bCompilationSuccessful)
	{
		Release(); // We release only if compilation was successful. (this makes hot reloading fault tolerant case because we can keep the older shaders running)

		ID3D11ShaderReflection* VertexShaderReflection, *PixelShaderReflection;
		ID3D11ShaderReflection* GeometryShaderReflection = nullptr, *HullShaderReflection = nullptr, *DomainShaderReflection = nullptr;

		Device->CreateVertexShader(VertexShaderBlob->GetBufferPointer(), VertexShaderBlob->GetBufferSize(), nullptr, &VertexShader);
		Device->CreatePixelShader(PixelShaderBlob->GetBufferPointer(), PixelShaderBlob->GetBufferSize(), nullptr, &PixelShader);

		D3DSetDebugName(VertexShader, VertexShaderInfo->GetDebugName());
		D3DSetDebugName(PixelShader, PixelShaderInfo->GetDebugName());

		D3DReflect(VertexShaderBlob->GetBufferPointer(), VertexShaderBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&VertexShaderReflection);
		D3DReflect(PixelShaderBlob->GetBufferPointer(), PixelShaderBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&PixelShaderReflection);

		if (GeometryShaderBlob)
		{
			Device->CreateGeometryShader(GeometryShaderBlob->GetBufferPointer(), GeometryShaderBlob->GetBufferSize(), nullptr, &GeometryShader);
			D3DSetDebugName(GeometryShader, GeometryShaderInfo->GetDebugName());
			D3DReflect(GeometryShaderBlob->GetBufferPointer(), GeometryShaderBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&GeometryShaderReflection);
		}

		if (DomainShaderBlob && HullShaderBlob)
		{
			Device->CreateHullShader(HullShaderBlob->GetBufferPointer(), HullShaderBlob->GetBufferSize(), nullptr, &HullShader);
			Device->CreateDomainShader(DomainShaderBlob->GetBufferPointer(), DomainShaderBlob->GetBufferSize(), nullptr, &DomainShader);
			
			D3DSetDebugName(HullShader, HullShaderInfo->GetDebugName());
			D3DSetDebugName(DomainShader, DomainShaderInfo->GetDebugName());

			D3DReflect(HullShaderBlob->GetBufferPointer(), HullShaderBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&HullShaderReflection);
			D3DReflect(DomainShaderBlob->GetBufferPointer(), DomainShaderBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&DomainShaderReflection);
		}

		CreateInputLayoutDescFromVertexShaderSignature(VertexShaderReflection, VertexShaderBlob, Device);

		MaterialParameters = Make_Unique<FMaterialParameters>(GraphicsContext, VertexShaderReflection, PixelShaderReflection, GeometryShaderReflection, HullShaderReflection, DomainShaderReflection);

		VertexShaderReflection->Release();
		PixelShaderReflection->Release();

		if (GeometryShaderReflection != nullptr)
			GeometryShaderReflection->Release();

		if (DomainShaderReflection != nullptr)
			DomainShaderReflection->Release();

		if (HullShaderReflection != nullptr)
			HullShaderReflection->Release();
	}
}
Exemplo n.º 22
0
void TgcDX11Effect::internalCreate()
{
	ID3D11Device* device = ((TgcDX11Renderer*)GuiController::Instance->renderer)->device;

	HRESULT result;
	ID3D10Blob* errorMessage = NULL;
	D3D_SHADER_MACRO* pDefines = NULL;
	ID3DInclude* pInclude = NULL;
	UINT flags2 = 0;

	//Compile vertex shader
	this->vertexShaderBuffer = NULL;
	result = D3DX11CompileFromFile(this->filePath.c_str(), pDefines, pInclude, this->description.vsFunctionName.c_str(), 
		TgcDX11Effect::VS_SHADER_TARGET, D3D10_SHADER_PACK_MATRIX_ROW_MAJOR | D3D10_SHADER_ENABLE_STRICTNESS, flags2, NULL, 
		&(this->vertexShaderBuffer), &errorMessage, NULL);
	if(FAILED(result))
	{
		if(errorMessage)
		{
			GuiController::Instance->logger->logError("Error loading DX11 vertex shader: " + this->description.vsFunctionName 
				+ ", Path: " + this->filePath + ", Error: " + getErrorMessage(errorMessage));
		}
		else
		{
			GuiController::Instance->logger->logError("Error loading DX11 vertex shader. Could not find file: " + this->filePath);
		}
		return;
	}


	//Compile pixel shader
	ID3D10Blob* pixelShaderBuffer = NULL;
	result = D3DX11CompileFromFile(this->filePath.c_str(), pDefines, pInclude, this->description.psFunctionName.c_str(), 
		TgcDX11Effect::PS_SHADER_TARGET, D3D10_SHADER_PACK_MATRIX_ROW_MAJOR | D3D10_SHADER_ENABLE_STRICTNESS, flags2, NULL, 
		&pixelShaderBuffer, &errorMessage, NULL);
	if(FAILED(result))
	{
		if(errorMessage)
		{
			GuiController::Instance->logger->logError("Error loading DX11 pixel shader: " + this->description.psFunctionName 
				+ ", Path: " + this->filePath + ", Error: " + getErrorMessage(errorMessage));
		}
		else
		{
			GuiController::Instance->logger->logError("Error loading DX11 pixel shader. Could not find file: " + this->filePath);
		}
		return;
	}

	//Create the vertex shader from the buffer.
	result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), this->vertexShaderBuffer->GetBufferSize(), NULL, &(this->vertexShader));
	if(FAILED(result))
	{
		GuiController::Instance->logger->logError("Error creating DX11 vertex shader: " + this->description.vsFunctionName + ", Path: " + this->filePath);
	}

    //Create the pixel shader from the buffer.
	result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &(this->pixelShader));
	if(FAILED(result))
	{
		GuiController::Instance->logger->logError("Error creating DX11 pixel shader: " + this->description.psFunctionName + ", Path: " + this->filePath);
	}

	//Release pixelShaderBuffer (vertexShaderBuffer no because is used later to create the InputLayout)
	pixelShaderBuffer->Release();
	pixelShaderBuffer = 0;
}
Exemplo n.º 23
0
	bool MultiTextureShader::InitializeShader(Graphics* graphics,std::wstring vertexShaderFilename,std::wstring pixelShaderFilename)
	{
		// create a little structure to handle
		// shader buffer and size
		struct ShaderBuffer
		{
			unsigned int Size;
			void* Buffer;
		};

		ShaderBuffer vertexBuffer, pixelBuffer;

		D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
		unsigned int numElements;
		D3D11_SAMPLER_DESC samplerDesc;
		ID3D11Device* device = graphics->GetDevice();


		memset(&vertexBuffer,0,sizeof(ShaderBuffer));
		memset(&pixelBuffer,0,sizeof(ShaderBuffer));
		// load the compiled shaders
		vertexBuffer.Buffer = LoadCompiledShader(vertexShaderFilename, vertexBuffer.Size);
		pixelBuffer.Buffer = LoadCompiledShader(pixelShaderFilename, pixelBuffer.Size);
		// set the shaders
		if(FAILED(device->CreateVertexShader(vertexBuffer.Buffer,vertexBuffer.Size,nullptr,&m_vertexShader)))
			return false;

		if(FAILED(device->CreatePixelShader(pixelBuffer.Buffer,pixelBuffer.Size,nullptr,&m_pixelShader)))
			return false;

		// create the vertex input layout
		polygonLayout[0].SemanticName = "POSITION";
		polygonLayout[0].SemanticIndex = 0;
		polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
		polygonLayout[0].InputSlot = 0;
		polygonLayout[0].AlignedByteOffset = 0;
		polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[0].InstanceDataStepRate = 0;

		polygonLayout[1].SemanticName = "TEXCOORD";
		polygonLayout[1].SemanticIndex = 0;
		polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
		polygonLayout[1].InputSlot = 0;
		polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
		polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[1].InstanceDataStepRate = 0;

		// get a count of the elements in the layout
		numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

		// create the vertex input layout
		if(FAILED(device->CreateInputLayout(polygonLayout,numElements,vertexBuffer.Buffer,
			vertexBuffer.Size,&m_layout)))
			return false;

		// released the vertex shader buffer and pixel shader buffers
		// since they are no longer needed
		delete vertexBuffer.Buffer;
		delete pixelBuffer.Buffer;

		// initialize our constant buffer
		m_matrixBuffer.Initialize(device);

		// create a texture sampler state description
		samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
		samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.MipLODBias = 0.0f;
		samplerDesc.MaxAnisotropy = 1;
		samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
		//memset(&samplerDesc.BorderColor,0,sizeof(FLOAT)*4);
		samplerDesc.BorderColor[0] = 0.0f;
		samplerDesc.BorderColor[1] = 0.0f;
		samplerDesc.BorderColor[2] = 0.0f;
		samplerDesc.BorderColor[3] = 0.0f;
		samplerDesc.MinLOD = 0;
		samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

		// create the texture sampler
		if(FAILED(device->CreateSamplerState(&samplerDesc,&m_sampleState)))
			return false;

		return true;
	}
Exemplo n.º 24
0
// WinMain
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
    HRESULT hr;


    // ウィンドウクラスを登録
    WNDCLASSEX wcex = {
        sizeof( WNDCLASSEX ),			// cbSize
        CS_HREDRAW | CS_VREDRAW,		// style
        WndProc,						// lpfnWndProc
        0,								// cbClsExtra
        0,								// cbWndExtra
        hInstance,						// hInstance
        NULL,							// hIcon
        NULL,							// hCursor
        ( HBRUSH )( COLOR_WINDOW + 1 ),	// hbrBackGround
        NULL,							// lpszMenuName
        g_className,					// lpszClassName
        NULL							// hIconSm
    };
    if ( ! RegisterClassEx( &wcex ) )
    {
        MessageBox( NULL, _T( "失敗: RegisterClassEx()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "RegisterClassEx: ok\n" ) );


    // ウィンドウサイズを計算
    RECT r = { 0, 0, 800, 450 };   // 800x450 (16:9)
    if ( ! AdjustWindowRect( &r, WS_OVERLAPPEDWINDOW, FALSE ) )
    {
        MessageBox( NULL, _T( "失敗: AdjustWindowRect()" ), _T( "エラー" ),  MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "AdjustWindowRect: ok (%d, %d)-(%d, %d)\n" ), r.left, r.top, r.right, r.bottom );


    // ウィンドウ生成
    HWND hWnd;
    hWnd = CreateWindow( g_className,
                         g_windowName,
                         WS_OVERLAPPEDWINDOW,
                         CW_USEDEFAULT,
                         0,
                         r.right - r.left,
                         r.bottom - r.top,
                         NULL,
                         NULL,
                         hInstance,
                         NULL );
    if ( hWnd == NULL )
    {
        MessageBox( NULL, _T( "失敗: CreateWindow()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "CreateWindow: ok\n" ) );


    // ウィンドウ表示
    ShowWindow(hWnd, nCmdShow);
    dtprintf( _T( "ShowWindow: ok\n" ) );



    // スワップチェイン設定
    DXGI_SWAP_CHAIN_DESC scDesc = {
        {
            1280,									// BufferDesc.Width
            720,									// BufferDesc.Height
            {
                60,									// BufferDesc.RefreshRate.Numerator
                1									// BufferDesc.RefreshRate.Denominator
            },
            DXGI_FORMAT_R16G16B16A16_FLOAT,			// BufferDesc.Format
            DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED,	// BufferDesc.ScanlineOrdering
            DXGI_MODE_SCALING_CENTERED				// BufferDesc.Scaling
        },
        {
            1,										// SampleDesc.Count
            0										// SampleDesc.Quality
        },
        DXGI_USAGE_RENDER_TARGET_OUTPUT,			// BufferUsage
        1,											// BufferCount
        hWnd,										// OutputWindow
        TRUE,										// Windowed
        DXGI_SWAP_EFFECT_DISCARD,					// SwapEffect
        DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH		// Flags
    };

    // Direct3D11 デバイス・デバイスコンテキスト・スワップチェーンを生成
    ID3D11Device        * pDevice        = NULL;
    ID3D11DeviceContext * pDeviceContext = NULL;
    IDXGISwapChain      * pSwapChain     = NULL;
    D3D_FEATURE_LEVEL     feature;
    hr = D3D11CreateDeviceAndSwapChain( NULL,
                                        D3D_DRIVER_TYPE_HARDWARE,
                                        NULL,
                                        0,
                                        NULL,
                                        0,
                                        D3D11_SDK_VERSION,
                                        &scDesc,
                                        &pSwapChain,
                                        &pDevice,
                                        &feature,
                                        &pDeviceContext );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: D3D11CreateDeviceAndSwapChain()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "D3D11CreateDeviceAndSwapChain: ok (pDevice: 0x%p, pDeviceContext: 0x%p, pSwapChain: 0x%p, feature: 0x%4x)\n" ),
              pDevice,
              pDeviceContext,
              pSwapChain,
              ( int ) feature );


    // バックバッファテクスチャを取得
    ID3D11Texture2D * pBackBuffer = NULL;
    hr = pSwapChain->GetBuffer( 0, __uuidof( pBackBuffer ), reinterpret_cast< void ** >( &pBackBuffer ) );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: IDXGISwapChain::GetBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "IDXGISwapChain::GetBuffer: ok (pBackBuffer: 0x%p)\n" ), pBackBuffer );


    // レンダーターゲットビューを生成
    ID3D11RenderTargetView * pRenderTargetView = NULL;
    hr = pDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRenderTargetView );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateRenderTargetView()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateRenderTargetView: ok (pRenderTargetView: 0x%p)\n" ), pRenderTargetView );


    // デプス・ステンシルバッファとなるテクスチャを生成
    D3D11_TEXTURE2D_DESC depthStencilBufferDesc = {
        1280,						// Width
        720,						// Height
        1,							// MipLevels
        1,							// ArraySize
        DXGI_FORMAT_D32_FLOAT,		// Format
        {
            1,						// SampleDesc.Count
            0						// SampleDesc.Quality
        },
        D3D11_USAGE_DEFAULT,		// Usage
        D3D11_BIND_DEPTH_STENCIL,	// BindFlags
        0,							// CPUAccessFlags
        0							// MiscFlags
    };

    ID3D11Texture2D * pDepthStencilBuffer = NULL;
    hr = pDevice->CreateTexture2D( &depthStencilBufferDesc, NULL, &pDepthStencilBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateTexture2D()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateTexture2D: ok (pDepthStencilBuffer: 0x%p)\n" ), pDepthStencilBuffer );

    // デプス・ステンシルビューを生成
    ID3D11DepthStencilView * pDepthStencilView = NULL;
    hr = pDevice->CreateDepthStencilView( pDepthStencilBuffer, NULL, &pDepthStencilView );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateDepthStencilView()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateDepthStencilView: ok (pDepthStencilView: 0x%p)\n" ), pDepthStencilView );


    // レンダーターゲットビューとデプス・ステンシルビューをバインド
    ID3D11RenderTargetView * pRenderTargetViews[] = { pRenderTargetView };
    pDeviceContext->OMSetRenderTargets( 1, pRenderTargetViews, pDepthStencilView );
    dtprintf( _T( "ID3D11DeviceContext::OMSetRenderTargets: ok\n" ) );

    // バックバッファはもうここでは使わない
    COM_SAFE_RELEASE( pBackBuffer );


    // ビューポートをバインド
    D3D11_VIEWPORT viewport = {
        0.0f,		// TopLeftX
        0.0f,		// TopLeftY
        1280.0f,		// Width
        720.0f,		// Height
        0.0f,		// MinDepth
        1.0f			// MaxDepth
    };
    pDeviceContext->RSSetViewports( 1, &viewport );
    dtprintf( _T( "ID3D11DeviceContext::RSSetViewports: ok\n" ) );


    // 頂点データ
    float vertices[ 8 ][ 7 ] = {
        //    Xaxis  Yaxis  Zaxis  赤     緑     青     Alpha
        { -0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  0.0f,  1.0f },   // 手前左上
        {  0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f },   // 手前右上
        {  0.5f, -0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f },   // 手前右下
        { -0.5f, -0.5f,  0.5f,  0.0f,  1.0f,  1.0f,  1.0f },   // 手前左下
        { -0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  1.0f },   // 奥左上
        {  0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  1.0f,  1.0f },   // 奥右上
        {  0.5f, -0.5f, -0.5f,  1.0f,  1.0f,  0.0f,  1.0f },   // 奥右下
        { -0.5f, -0.5f, -0.5f,  1.0f,  1.0f,  1.0f,  1.0f }    // 奥左下
    };

    // 頂点バッファを生成
    D3D11_BUFFER_DESC vertexBufferDesc = {
        sizeof( vertices ),			// ByteWidth
        D3D11_USAGE_DEFAULT,		// Usage
        D3D11_BIND_VERTEX_BUFFER,	// BindFlags
        0,							// CPUAccessFlags
        0,							// MiscFlags
        0							// StructureByteStride
    };
    D3D11_SUBRESOURCE_DATA vertexResourceData = { vertices };

    ID3D11Buffer * pVertexBuffer = NULL;
    hr = pDevice->CreateBuffer( &vertexBufferDesc, &vertexResourceData, &pVertexBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pVertexBuffer: 0x%p)\n" ), pVertexBuffer );

    // 頂点バッファをバインド
    UINT strides[] = { sizeof( float ) * 7 };
    UINT offsets[] = { 0 };
    pDeviceContext->IASetVertexBuffers( 0, 1, &pVertexBuffer, strides, offsets );
    dtprintf( _T( "ID3D11DeviceContext::IASetVertexBuffers: ok\n" ) );


    // インデックスデータ
    unsigned int indices[] = { 0, 1, 2, 0, 2, 3,    // 手前
                               4, 0, 3, 4, 3, 7,    // 左
                               1, 5, 6, 1, 6, 2,    // 右
                               0, 4, 5, 0, 5, 1,    // 上
                               2, 6, 7, 2, 7, 3,    // 下
                               5, 4, 7, 5, 7, 6
                             };  // 裏

    // インデックスバッファを生成
    D3D11_BUFFER_DESC indexBufferDesc = {
        sizeof( indices ),				// ByteWidth
        D3D11_USAGE_DEFAULT,			// Usage
        D3D11_BIND_INDEX_BUFFER,		// BindFlags
        0,								// CPUAccessFlags
        0,								// MiscFlags
        0								// StructureByteStride
    };
    D3D11_SUBRESOURCE_DATA indexResourceData = { indices };

    ID3D11Buffer * pIndexBuffer = NULL;
    hr = pDevice->CreateBuffer( &indexBufferDesc, &indexResourceData, &pIndexBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pIndexBuffer: 0x%p)\n" ), pIndexBuffer );

    // インデックスバッファをバインド
    pDeviceContext->IASetIndexBuffer( pIndexBuffer, DXGI_FORMAT_R32_UINT, 0 );
    dtprintf( _T( "ID3D11DeviceContext::IASetIndexBuffer: ok\n" ) );


    // プリミティブタイプを設定
    pDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
    dtprintf( _T( "ID3D11DeviceContext::IASetPrimitiveTopology: ok\n" ) );


    // 頂点シェーダ用の定数バッファを作成
    D3D11_BUFFER_DESC VSConstantBufferDesc = {
        sizeof( D3DXMATRIX ) * 3,		// ByteWidth
        D3D11_USAGE_DYNAMIC,			// Usage
        D3D11_BIND_CONSTANT_BUFFER,		// BindFlags
        D3D11_CPU_ACCESS_WRITE,			// CPUAccessFlags
        0,								// MiscFlags
        0								// StructureByteStride
    };

    ID3D11Buffer * pVSConstantBuffer = NULL;
    hr = pDevice->CreateBuffer( &VSConstantBufferDesc, NULL, &pVSConstantBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pVSConstantBuffer: 0x%p)\n" ), pVSConstantBuffer );

    // 定数バッファをバインド
    pDeviceContext->VSSetConstantBuffers( 0, 1, &pVSConstantBuffer );
    dtprintf( _T( "ID3D11DeviceContext::VSSetConstantBuffers: ok\n" ) );


    // 頂点シェーダを作成
    ID3D11VertexShader * pVertexShader = NULL;
    hr = pDevice->CreateVertexShader( g_vs_perspective, sizeof( g_vs_perspective ), NULL, &pVertexShader );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateVertexShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateVertexShader: ok (pVertexShader: 0x%p)\n" ), pVertexShader );

    // ピクセルシェーダを作成
    ID3D11PixelShader * pPixelShader = NULL;
    hr = pDevice->CreatePixelShader( g_ps_constant, sizeof( g_ps_constant ), NULL, &pPixelShader );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreatePixelShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreatePixelShader: ok (pPixelShader: 0x%p)\n" ), pPixelShader );

    // シェーダをバインド
    pDeviceContext->VSSetShader( pVertexShader, NULL, 0 );
    dtprintf( _T( "ID3D11DeviceContext::VSSetShader: ok\n" ) );
    pDeviceContext->PSSetShader( pPixelShader, NULL, 0 );
    dtprintf( _T( "ID3D11DeviceContext::PSSetShader: ok\n" ) );
    pDeviceContext->GSSetShader( NULL, NULL, 0 );
    pDeviceContext->HSSetShader( NULL, NULL, 0 );
    pDeviceContext->DSSetShader( NULL, NULL, 0 );


    // 入力エレメント記述子
    D3D11_INPUT_ELEMENT_DESC verticesDesc[] = {
        { "IN_POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,    0, 0,               D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "IN_COLOR",    0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, sizeof(float)*3, D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };

    // 入力レイアウトを生成
    ID3D11InputLayout * pInputLayout = NULL;
    hr = pDevice->CreateInputLayout( verticesDesc, 2, g_vs_perspective, sizeof( g_vs_perspective ), &pInputLayout );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateInputLayout()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateInputLayout: ok (pInputLayout: 0x%p)\n" ), pInputLayout );

    // 入力レイアウトをバインド
    pDeviceContext->IASetInputLayout( pInputLayout );
    dtprintf( _T( "ID3D11DeviceContext::IASetInputLayout: ok\n" ) );


    // ラスタライザステートを生成
    D3D11_RASTERIZER_DESC rasterizerStateDesc = {
        D3D11_FILL_SOLID,		// FillMode
//		D3D11_FILL_WIREFRAME,	// FillMode (ワイヤーフレーム表示)
        D3D11_CULL_BACK,		// CullMode
//		D3D11_CULL_NONE,		// CullMode (カリングなし)
        FALSE,					// FrontCounterClockwise
        0,						// DepthBias
        0.0f,					// DepthBiasClamp
        0.0f,					// SlopeScaledDepthBias
        TRUE,					// DepthClipEnable
        FALSE,					// ScissorEnable
        FALSE,					// MultisampleEnable
        FALSE					// AntialiasedLineEnable
    };

    ID3D11RasterizerState * pRasterizerState = NULL;
    hr = pDevice->CreateRasterizerState( &rasterizerStateDesc, &pRasterizerState );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateRasterizerState()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateRasterizerState: ok (pRasterizerState: 0x%p)\n" ), pRasterizerState );

    // ラスタライザステートをバインド
    pDeviceContext->RSSetState( pRasterizerState );
    dtprintf( _T( "ID3D11DeviceContext::RSSetState: ok\n" ) );


    // デプス・ステンシルステートを生成
    D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc = {
        TRUE,								// DepthEnable
        D3D11_DEPTH_WRITE_MASK_ALL,			// DepthWriteMask
        D3D11_COMPARISON_LESS,				// DepthFunc
        FALSE,								// StencilEnable
        D3D11_DEFAULT_STENCIL_READ_MASK,	// StencilReadMask
        D3D11_DEFAULT_STENCIL_WRITE_MASK,	// StencilWriteMask
        {
            D3D11_STENCIL_OP_KEEP,			// FrontFace.StencilFailOp
            D3D11_STENCIL_OP_KEEP,			// FrontFace.StencilDepthFailOp
            D3D11_STENCIL_OP_KEEP,			// FrontFace.StencilPassOp
            D3D11_COMPARISON_ALWAYS			// FrontFace.StencilFunc
        },
        {
            D3D11_STENCIL_OP_KEEP,			// BackFace.StencilFailOp
            D3D11_STENCIL_OP_KEEP,			// BackFace.StencilDepthFailOp
            D3D11_STENCIL_OP_KEEP,			// BackFace.StencilPassOp
            D3D11_COMPARISON_ALWAYS			// BackFace.StencilFunc
        }
    };

    ID3D11DepthStencilState * pDepthStencilState = NULL;
    hr = pDevice->CreateDepthStencilState( &depthStencilStateDesc, &pDepthStencilState );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateDepthStencilState()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateDepthStencilState: ok (pDepthStencilState: 0x%p)\n" ), pDepthStencilState );

    // デプス・ステンシルステートをバインド
    pDeviceContext->OMSetDepthStencilState( pDepthStencilState, 0 );
    dtprintf( _T( "ID3D11DeviceContext::OMSetDepthStencilState: ok\n" ) );



    MSG msg;

    while ( 1 )
    {
        // メッセージを取得
        if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        {
            if ( msg.message == WM_QUIT )
            {
                dtprintf( _T( "PeekMessage: WM_QUIT\n" ) );
                break;
            }
            // メッセージ処理
            DispatchMessage( &msg );
        }
        else
        {
            HRESULT hr;

            static unsigned int count = 0;

            float theta = ( count++ / 200.0f ) * ( 3.141593f / 2.0f );


            // World-View-Projection 行列をそれぞれ生成
            D3DXMATRIX world, view, projection;

            D3DXMatrixIdentity( &world );

            const D3DXVECTOR3 eye( 1.8f * 1.414214f * -cosf( theta ), 1.8f, 1.8f * 1.414214f * sinf( theta ) );
            const D3DXVECTOR3 at( 0.0f, 0.0f, 0.0f );
            const D3DXVECTOR3 up( 0.0f, 1.0f, 0.0f );
            D3DXMatrixLookAtRH( &view, &eye, &at, &up );

            D3DXMatrixPerspectiveFovRH( &projection, 3.141593f / 4.0f, 1280.0f / 720.0f, 1.0f, 10000.0f );


            // 頂点シェーダ用定数バッファへアクセス
            D3D11_MAPPED_SUBRESOURCE mapped;
            hr = pDeviceContext->Map( pVSConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped );
            if ( SUCCEEDED( hr ) )
            {
                D3DXMATRIX * mapped_m = static_cast< D3DXMATRIX * >( mapped.pData );

                mapped_m[0] = world;
                mapped_m[1] = view;
                mapped_m[2] = projection;

                // 後始末
                pDeviceContext->Unmap( pVSConstantBuffer, 0 );
            }


            // レンダーターゲットビューをクリア
            const float clear[ 4 ] = { 0.0f, 0.0f, 0.3f, 1.0f };	// RGBA
            pDeviceContext->ClearRenderTargetView( pRenderTargetView, clear );

            // デプス・ステンシルビューをクリア
            pDeviceContext->ClearDepthStencilView( pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0 );


            // 描画
            pDeviceContext->DrawIndexed( 36, 0, 0 );

            pSwapChain->Present( 1, 0 );

            // ちょっとだけ待つ
            Sleep( 5 );
        }
    }



    // シェーダをアンバインド
    pDeviceContext->VSSetShader( NULL, NULL, 0 );
    pDeviceContext->PSSetShader( NULL, NULL, 0 );

    // デバイス・リソース解放
    COM_SAFE_RELEASE( pDepthStencilState );
    COM_SAFE_RELEASE( pRasterizerState );
    COM_SAFE_RELEASE( pInputLayout );
    COM_SAFE_RELEASE( pPixelShader );
    COM_SAFE_RELEASE( pVertexShader );
    COM_SAFE_RELEASE( pVSConstantBuffer );
    COM_SAFE_RELEASE( pIndexBuffer );
    COM_SAFE_RELEASE( pVertexBuffer );
    COM_SAFE_RELEASE( pDepthStencilView );
    COM_SAFE_RELEASE( pDepthStencilBuffer );
    COM_SAFE_RELEASE( pRenderTargetView );
    COM_SAFE_RELEASE( pSwapChain );
    COM_SAFE_RELEASE( pDeviceContext );
    COM_SAFE_RELEASE( pDevice );


    return msg.wParam;
}
Exemplo n.º 25
0
		bool ShadowMappingShader::InitializeShader(const char * i_vsFileName, const char * i_psFileName)
		{
			HRESULT result;
			ID3D10Blob* errorMessage;
			ID3D10Blob* vertexShaderBuffer;
			ID3D10Blob* pixelShaderBuffer;
			D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
			unsigned int numElements;
			D3D11_SAMPLER_DESC samplerDesc;
			D3D11_BUFFER_DESC matrixBufferDesc;
			D3D11_BUFFER_DESC lightBufferDesc;
			D3D11_BUFFER_DESC lightBufferDesc2;

			// Initialize the pointers this function will use to null.
			errorMessage = 0;
			vertexShaderBuffer = 0;
			pixelShaderBuffer = 0;

			// Compile the vertex shader code.
			result = D3DX11CompileFromFile(i_vsFileName, NULL, NULL, "ShadowVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
				&vertexShaderBuffer, &errorMessage, NULL);
			if (FAILED(result))
			{
				// If the shader failed to compile it should have writen something to the error message.
				if (errorMessage)
				{
					outputShaderErrorMessage(errorMessage, i_vsFileName);
				}
				// If there was nothing in the error message then it simply could not find the shader file itself.
				else
				{
					MessageBox(System::Window::GetWindwsHandle(), i_vsFileName, "Missing Shader File", MB_OK);
				}

				return false;
			}

			// Compile the pixel shader code.
			result = D3DX11CompileFromFile(i_psFileName, NULL, NULL, "ShadowPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
				&pixelShaderBuffer, &errorMessage, NULL);
			if (FAILED(result))
			{
				// If the shader failed to compile it should have writen something to the error message.
				if (errorMessage)
				{
					outputShaderErrorMessage(errorMessage, i_psFileName);
				}
				// If there was nothing in the error message then it simply could not find the file itself.
				else
				{
					MessageBox(System::Window::GetWindwsHandle(), i_psFileName, "Missing Shader File", MB_OK);
				}

				return false;
			}

			ID3D11Device* device = GraphicsDX::GetDevice();

			// Create the vertex shader from the buffer.
			result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader);
			if (FAILED(result))
			{
				return false;
			}

			// Create the pixel shader from the buffer.
			result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader);
			if (FAILED(result))
			{
				return false;
			}

			// Create the vertex input layout description.
			polygonLayout[0].SemanticName = "POSITION";
			polygonLayout[0].SemanticIndex = 0;
			polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
			polygonLayout[0].InputSlot = 0;
			polygonLayout[0].AlignedByteOffset = 0;
			polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
			polygonLayout[0].InstanceDataStepRate = 0;

			polygonLayout[1].SemanticName = "TEXCOORD";
			polygonLayout[1].SemanticIndex = 0;
			polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
			polygonLayout[1].InputSlot = 0;
			polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
			polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
			polygonLayout[1].InstanceDataStepRate = 0;

			polygonLayout[2].SemanticName = "NORMAL";
			polygonLayout[2].SemanticIndex = 0;
			polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
			polygonLayout[2].InputSlot = 0;
			polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
			polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
			polygonLayout[2].InstanceDataStepRate = 0;

			// Get a count of the elements in the layout.
			numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

			// Create the vertex input layout.
			result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(),
				&m_layout);
			if (FAILED(result))
			{
				return false;
			}

			// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
			vertexShaderBuffer->Release();
			vertexShaderBuffer = 0;

			pixelShaderBuffer->Release();
			pixelShaderBuffer = 0;

			// Create a wrap texture sampler state description.
			samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
			samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
			samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
			samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
			samplerDesc.MipLODBias = 0.0f;
			samplerDesc.MaxAnisotropy = 1;
			samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
			samplerDesc.BorderColor[0] = 0;
			samplerDesc.BorderColor[1] = 0;
			samplerDesc.BorderColor[2] = 0;
			samplerDesc.BorderColor[3] = 0;
			samplerDesc.MinLOD = 0;
			samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

			// Create the texture sampler state.
			result = device->CreateSamplerState(&samplerDesc, &m_sampleStateWrap);
			if (FAILED(result))
			{
				return false;
			}

			// Create a clamp texture sampler state description.
			samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
			samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
			samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;

			// Create the texture sampler state.
			result = device->CreateSamplerState(&samplerDesc, &m_sampleStateClamp);
			if (FAILED(result))
			{
				return false;
			}

			// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
			matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
			matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
			matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
			matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
			matrixBufferDesc.MiscFlags = 0;
			matrixBufferDesc.StructureByteStride = 0;

			// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
			result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer);
			if (FAILED(result))
			{
				return false;
			}

			// Setup the description of the light dynamic constant buffer that is in the pixel shader.
			lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
			lightBufferDesc.ByteWidth = sizeof(LightBufferType);
			lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
			lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
			lightBufferDesc.MiscFlags = 0;
			lightBufferDesc.StructureByteStride = 0;

			// Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class.
			result = device->CreateBuffer(&lightBufferDesc, NULL, &m_lightBuffer);
			if (FAILED(result))
			{
				return false;
			}

			// Setup the description of the light dynamic constant buffer that is in the vertex shader.
			lightBufferDesc2.Usage = D3D11_USAGE_DYNAMIC;
			lightBufferDesc2.ByteWidth = sizeof(LightBufferType2);
			lightBufferDesc2.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
			lightBufferDesc2.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
			lightBufferDesc2.MiscFlags = 0;
			lightBufferDesc2.StructureByteStride = 0;

			// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
			result = device->CreateBuffer(&lightBufferDesc2, NULL, &m_lightBuffer2);
			if (FAILED(result))
			{
				return false;
			}

			return true;
		}