Beispiel #1
0
bool DemoBase::CompileD3DShader( char* filePath, char* entry, char* shaderModel, ID3DBlob** buffer )
{
	DWORD shaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;

#if defined(DEBUG) || defined(_DEBUG)
	shaderFlags |= D3DCOMPILE_DEBUG;
#endif

	ID3DBlob* errorBuffer = 0;
	HRESULT result;

	result = D3DX11CompileFromFileA(filePath, 0, 0, entry, shaderModel, shaderFlags, 0, 0, buffer, &errorBuffer, 0);

	if (FAILED(result))
	{
		if (errorBuffer != 0)
		{
			MessageBoxA(hwnd_, (LPCSTR)errorBuffer->GetBufferPointer(), "", NULL);
			OutputDebugStringA((char*)errorBuffer->GetBufferPointer());
			errorBuffer->Release();
		}

		return false;
	}

	if (errorBuffer != 0)
		errorBuffer->Release();

	return true;
}
Beispiel #2
0
bool Graphics::CompileD3DShader( char* filePath, char* entry, char* shaderModel, ID3DBlob** buffer )
{
	DWORD shaderFlags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_DEBUG;

	ID3DBlob* errorBuffer =0 ;
	HRESULT result = 0;

	result = D3DX11CompileFromFileA(filePath, 0, 0 , entry, shaderModel, shaderFlags, 0, 0, buffer, &errorBuffer, 0);

	if (FAILED(result))
	{
		if (errorBuffer != 0)
		{
			NAIA_ERROR("Unnable to compile shader!");
			NAIA_ERROR((char*) errorBuffer->GetBufferPointer());
			errorBuffer->Release();
		}

		return false;
	}

	if (errorBuffer != 0)
		errorBuffer->Release();

	return true;
}
Beispiel #3
0
bool scShader::Compile( ID3DBlob** buffer )
{
	DWORD shaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;

	ID3DBlob* errorBuffer = 0;
	HRESULT result;

	result = D3DX11CompileFromFileA(mPath.c_str(), 0, 0, mEntry.c_str(), mShaderModel.c_str(),
		shaderFlags, 0, 0, buffer, &errorBuffer, 0 );

	if( FAILED( result ) )
	{
		if( errorBuffer != 0 )
		{
			scErrMsg( ( char* )errorBuffer->GetBufferPointer( ) );
			errorBuffer->Release( );
		}
		return false;
	}

	if( errorBuffer != 0 )
	{
		scErrMsg( ( char* )errorBuffer->GetBufferPointer( ) );
		errorBuffer->Release( );
	}

	return true;
}
Beispiel #4
0
bool D3D11Shader::loadHLSLBlob( ID3D10Blob** blob, char* filename, char* fcnName, const char* shaderModel )
{
  ID3D10Blob *errorblob;

  if( !DX_CHECK( D3DX11CompileFromFileA(
    filename,
    NULL, NULL,
    fcnName,
    shaderModel, // usually "ps_5_0" or "vs_5_0"
    D3D10_SHADER_ENABLE_STRICTNESS, NULL,
    NULL,
    blob, &errorblob,
    NULL ), "compiling fx" ) )
  {
    if( !errorblob )
    {
      error( "%s shader file not found!", filename ) ;
      return false ;
    }
    else
    {
      int size = errorblob->GetBufferSize() ;
      char* errstr = (char*)malloc( size+1 ) ;
      strncpy( errstr, (char*)errorblob->GetBufferPointer(), size ) ;
      errstr[ size ] = 0 ;
      error( errstr );
      free( errstr ) ;
    }
    SAFE_RELEASE( errorblob );
    bail( "Couldn't compile your fx file", true ) ; // (exits)
    return false ;
  }
    
  return true ; // successful load  
}
Beispiel #5
0
bool ComputeShader::createFromFile(ID3D11Device* currDevice, char* filePath, char* shaderEntryPoint)
{
	UINT compileFlags = 0;

	#if defined(DEBUG) | defined(_DEBUG)
		compileFlags |= D3DCOMPILE_DEBUG;
	#else
		compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL3;
	#endif

	try
	{
		D3DX11CompileFromFileA(filePath, 0, NULL, shaderEntryPoint, "cs_5_0", compileFlags, NULL, NULL, &mEffectBlob, &mCompilerErrors, NULL);

		if (!mEffectBlob)
			throw (char*) mCompilerErrors->GetBufferPointer();

		HRESULT error = currDevice->CreateComputeShader(mEffectBlob->GetBufferPointer(), mEffectBlob->GetBufferSize(), NULL, &mComputeShader);

		if (!mComputeShader)
			throw error;

	}
	catch (char* e)
	{
		std::cout << e;
		return false;
	}

	return true;
}
Beispiel #6
0
//VERTEX SHADER
HRESULT ACD3D::CompileVS(std::string path, VertexFormat vertexFormat, ACVertexShader** ppOutVertexShaderPtr)
{
	*ppOutVertexShaderPtr = new ACVertexShader();

	//compila o VS 
	ID3DBlob* pVSBuf = nullptr;
	ID3DBlob* pError = nullptr;

	//se estiver em debug ele compila o shader para ser debugado, em release ele é otimizado
	DWORD dwShaderFlags = 0;
	#if defined( DEBUG ) || defined( _DEBUG )
    dwShaderFlags |= D3DCOMPILE_DEBUG;
    #endif

	HRESULT hr = 0;
	hr = D3DX11CompileFromFileA(path.c_str(), 
								nullptr, 
								nullptr, 
								"main", 
								"vs_4_0", 
								dwShaderFlags, 
								0, 
								nullptr, 
								&pVSBuf, 
								&pError, 
								nullptr );

    if( FAILED( hr ) )
    {
		char* pCompileErrors = static_cast<char*>(pError->GetBufferPointer());
		MessageBoxA(nullptr, pCompileErrors, "Error vS", MB_OK | MB_ICONERROR);
		Log("[ERROR] Erro ao carregar vertexshader. CompileVS(): %s", pCompileErrors); 
        hr = AC_FAIL;
    }
	else
	{
		//cria o vertexbuffer
		ID3D11VertexShader* pVS;
		ACD3DGlobals::G_pD3dDevice->CreateVertexShader( ( DWORD* )pVSBuf->GetBufferPointer(),
														  pVSBuf->GetBufferSize(),
														  nullptr,
														  &pVS);

		(*ppOutVertexShaderPtr)->pVS = pVS;
		(*ppOutVertexShaderPtr)->Format = vertexFormat;

		//cria o layout de vertice
		hr = ACD3DVertexLayoutProvider::CreateInputLayout(ACD3DGlobals::G_pD3dDevice, pVSBuf, vertexFormat);
	}

	SAFE_RELEASE(pVSBuf);
	SAFE_RELEASE(pError);

	return hr;
};
Beispiel #7
0
//--------------------------------------------------------------------------------------
// Find and compile the specified shader
//--------------------------------------------------------------------------------------
HRESULT D3D11VShader::CompileShaderFromFile(const CHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut, std::vector<D3D10_SHADER_MACRO>& makros)
{
	HRESULT hr = S_OK;

	char dir[260];
	GetCurrentDirectoryA(260, dir);
	SetCurrentDirectoryA(Engine::GAPI->GetStartDirectory().c_str());

	DWORD dwShaderFlags = 0;
#if defined( DEBUG ) || defined( _DEBUG )
	// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
	// Setting this flag improves the shader debugging experience, but still allows 
	// the shaders to be optimized and to run exactly the way they will run in 
	// the release configuration of this program.
	//dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif

	// Construct makros
	std::vector<D3D10_SHADER_MACRO> m;
	D3D11GraphicsEngine::ConstructShaderMakroList(m);
	
	// Push these to the front
	m.insert(m.begin(), makros.begin(), makros.end());

	ID3DBlob* pErrorBlob;
	hr = D3DX11CompileFromFileA(szFileName, &m[0], NULL, szEntryPoint, szShaderModel,
		dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL);
	if (FAILED(hr))
	{
		LogInfo() << "Shader compilation failed!";
		if (pErrorBlob != NULL)
		{

			LogErrorBox() << (char*)pErrorBlob->GetBufferPointer() << "\n\n (You can ignore the next error from Gothic about too small video memory!)";
			pErrorBlob->Release();
		}

		SetCurrentDirectoryA(dir);
		return hr;
	}
	if (pErrorBlob)
	{
		/*if(Engine->SwapchainCreated())
		Engine->GetConsole()->PostConsoleMessage((char*)pErrorBlob->GetBufferPointer());
		else
		LogWarnBox() << (char*)pErrorBlob->GetBufferPointer() << "\n\n (You can ignore the next error from Gothic about too small video memory!)";
		*/
		pErrorBlob->Release();
	}

	SetCurrentDirectoryA(dir);
	return S_OK;
}
Beispiel #8
0
//GEOMETRY SHADER
HRESULT ACD3D::CompileGS(std::string path, ACGeometryShader** ppOutGeometryShaderPtr)
{
	*ppOutGeometryShaderPtr = new ACGeometryShader();

	//compila o GS 
	ID3DBlob* pGSBuf = nullptr;
	ID3DBlob* pError = nullptr;

	//se estiver em debug ele compila o shader para ser debugado, em release ele é otimizado
	DWORD dwShaderFlags = 0;
	#if defined( DEBUG ) || defined( _DEBUG )
    dwShaderFlags |= D3DCOMPILE_DEBUG;
    #endif

	HRESULT hr = 0;
	hr = D3DX11CompileFromFileA(path.c_str(), 
								nullptr, 
								nullptr, 
								"main", 
								"gs_4_0", 
								dwShaderFlags, 
								0, 
								nullptr, 
								&pGSBuf, 
								&pError, 
								nullptr );

    if( FAILED( hr ) )
    {
		char* pCompileErrors = static_cast<char*>(pError->GetBufferPointer());
		MessageBoxA(nullptr, pCompileErrors, "Error GS", MB_OK | MB_ICONERROR);
		Log("[ERROR] Erro ao carregar geometryshader. CompileGS(): %s", pCompileErrors); 
        hr = AC_FAIL;
    }
	else
	{
		//cria o geometrybuffer
		ID3D11GeometryShader* pGS;
		ACD3DGlobals::G_pD3dDevice->CreateGeometryShader( ( DWORD* )pGSBuf->GetBufferPointer(),
														  pGSBuf->GetBufferSize(),
														  nullptr,
														  &pGS);

		(*ppOutGeometryShaderPtr)->pGS = pGS;

		hr = AC_OK;
	}

	SAFE_RELEASE(pGSBuf);
	SAFE_RELEASE(pError);

	return hr;
};
Beispiel #9
0
	HRESULT CompileShaderFromFile(LPCSTR szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut)
	{
		HRESULT hr = S_OK;
		ID3DBlob* pErrorBlob;
		hr = D3DX11CompileFromFileA(szFileName, NULL, NULL, szEntryPoint, szShaderModel, D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, ppBlobOut, &pErrorBlob, NULL);
		if(FAILED(hr))
		{
			OutputDebugStringA((char*)pErrorBlob->GetBufferPointer());
			SAFE_RELEASE(pErrorBlob);
			return hr;
		}
		SAFE_RELEASE(pErrorBlob);

		return S_OK;
	}
Beispiel #10
0
ID3D11PixelShader* Shader::InitPixelShader(const std::string& fileName, const std::string& funcName){
	ID3D11PixelShader* pPShader;
	ID3D10Blob* errBuffer;

	//pixel shader
	if ( FAILED( D3DX11CompileFromFileA(fileName.c_str(), NULL, NULL, funcName.c_str(), "ps_5_0",  D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &psBuffer, &errBuffer, NULL) ) ){
		if (errBuffer){
			LOG((LPCSTR)errBuffer->GetBufferPointer());
			SAFERELEASE(errBuffer);
		}else{
			LOG("Shader: Pixel shader file not found");
		}
		pPShader = NULL;
	}else{
		if ( FAILED( pDevice->CreatePixelShader(psBuffer->GetBufferPointer(), psBuffer->GetBufferSize(), NULL, &pPShader) ) ){
			pPShader = NULL;
			SAFERELEASE(psBuffer);
		}
	}

	return pPShader;
}
Beispiel #11
0
ID3D11VertexShader* Shader::InitVertexShader(const std::string& fileName, const std::string& funcName){
	ID3D11VertexShader* pVShader = NULL;
	ID3D10Blob* errBuffer;

	//vertex shader
	if ( FAILED( D3DX11CompileFromFileA(fileName.c_str(), NULL, NULL, funcName.c_str(), "vs_5_0",  D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vsBuffer, &errBuffer, NULL) ) ){
		if (errBuffer){
			LOG((LPCSTR)errBuffer->GetBufferPointer());
			SAFERELEASE(errBuffer);
		}else{
			LOG("Shader: Vertex shader file not found");
		}
		pVShader = NULL;
	}else{
		if ( FAILED( pDevice->CreateVertexShader(vsBuffer->GetBufferPointer(), vsBuffer->GetBufferSize(), NULL, &pVShader) ) ){
			pVShader = NULL;
			SAFERELEASE(vsBuffer);
		}
	}

	return pVShader;
}
void Terrain::init(ID3D11Device* device)
{
    ID3D11DeviceContext* deviceContext;
    device->GetImmediateContext(&deviceContext);

    ID3DBlob* errorBlob;
    ID3DBlob* shaderBlob;

    HRESULT result = D3DX11CompileFromFileA("Content\\Effects\\SimpleTerrain.fx", 0, 0, 0, "fx_5_0", 0, 0, 0, &shaderBlob, &errorBlob, 0);

    char* errorBuffer;
    if(errorBlob)
    {
        errorBuffer = (char*)errorBlob->GetBufferPointer();
    }

    result = D3DX11CreateEffectFromMemory(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), 0, device, &effect);

    if(shaderBlob)
        shaderBlob->Release();
    if(errorBlob)
        errorBlob->Release();

    // vertex buffer
    TerrainVertex vertices[] =
    {
        {Vector3(0.0f, 0, INSTANCE_SIZE), Vector3::up, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), Vector2(0, 0)},
        {Vector3(INSTANCE_SIZE, 0, INSTANCE_SIZE), Vector3::up, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), Vector2(1, 0)},
        {Vector3(0.0f, 0, 0.0f), Vector3::up, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), Vector2(0, 1)},
        {Vector3(INSTANCE_SIZE, 0, 0.0f), Vector3::up, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), Vector2(1, 1)}
    };

    D3D11_BUFFER_DESC vertexBufferDesc;
    ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));

    vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    vertexBufferDesc.ByteWidth = sizeof(vertices);
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = 0;

    D3D11_SUBRESOURCE_DATA vertexData;
    ZeroMemory( &vertexData, sizeof(D3D11_SUBRESOURCE_DATA) );
    vertexData.pSysMem = vertices;

    device->CreateBuffer(&vertexBufferDesc, &vertexData, &vertexBuffer);

    // Instance Buffer
    TerrainInstance instances[INSTANCE_COUNT];
    for(int i = 0; i < INSTANCE_COUNT_X; ++i)
        for(int j = 0; j < INSTANCE_COUNT_Y; ++j)
            instances[i * INSTANCE_COUNT_X + j].position = Vector3((float)i*INSTANCE_SIZE, 0, (float)j*INSTANCE_SIZE);

    D3D11_BUFFER_DESC instanceBufferDesc;
    ZeroMemory(&instanceBufferDesc, sizeof(D3D11_BUFFER_DESC));

    instanceBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    instanceBufferDesc.ByteWidth = sizeof(instances);
    instanceBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    instanceBufferDesc.CPUAccessFlags = 0;

    D3D11_SUBRESOURCE_DATA instanceData;
    ZeroMemory(&instanceData, sizeof(D3D11_SUBRESOURCE_DATA));
    instanceData.pSysMem = instances;

    device->CreateBuffer(&instanceBufferDesc, &instanceData, &instanceBuffer);

    // index buffer
    unsigned indices[] = { 0, 1, 2, 3 };
    indexCount = sizeof(indices) / sizeof(unsigned);

    D3D11_BUFFER_DESC indexBufferDesc;
    ZeroMemory(&indexBufferDesc, sizeof(D3D11_BUFFER_DESC));
    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(indices);
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;

    D3D11_SUBRESOURCE_DATA indexData;
    ZeroMemory(&indexData, sizeof(D3D11_SUBRESOURCE_DATA));
    indexData.pSysMem = indices;

    device->CreateBuffer(&indexBufferDesc, &indexData, &indexBuffer);

    D3D11_INPUT_ELEMENT_DESC inputElementDesc[] =
    {
        {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
        {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
        {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0},
        {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 40, D3D11_INPUT_PER_VERTEX_DATA, 0},
        {"TEXCOORD", 1, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1}
    };

    int inputElementCount = sizeof(inputElementDesc) / sizeof(D3D11_INPUT_ELEMENT_DESC);

    technique = effect->GetTechniqueByIndex(0);
    pass = technique->GetPassByIndex(0);

    D3DX11_PASS_DESC passDesc;
    pass->GetDesc(&passDesc);

    result = device->CreateInputLayout(inputElementDesc, inputElementCount,
                                       passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &inputLayout);

    DXUTGetGlobalResourceCache().CreateTextureFromFile(device, deviceContext, L"Content/Textures/Terrain/Grass.dds", &surfaceTexture);
    evSurfaceTexture = effect->GetVariableByName("SurfaceTexture")->AsShaderResource();
    evWorld = effect->GetVariableByName("World")->AsMatrix();
    evViewProjection = effect->GetVariableByName("ViewProjection")->AsMatrix();

    evSurfaceTexture->SetResource(surfaceTexture);

    world = Matrix::createTranslation((-INSTANCE_COUNT_X * INSTANCE_SIZE) / 2, 0, (-INSTANCE_COUNT_Y * INSTANCE_SIZE) / 2);

    deviceContext->Release();
}
Beispiel #13
0
	bool D3D11EffectMaterial::LoadFromFile(const char* szFile)
	{
		ID3D10Blob* pBlob = NULL;
		ID3D10Blob* pErrorBlob = NULL;

		if( FAILED( D3DX11CompileFromFileA( szFile, NULL, NULL, NULL, "fx_5_0", D3DCOMPILE_ENABLE_STRICTNESS, NULL, NULL, &pBlob, &pErrorBlob, NULL ) ) )
		{
			OutputDebugInfo(pErrorBlob);
			
			return false;
		}

		OutputDebugInfo(pErrorBlob);

		HRESULT ret = D3DX11CreateEffectFromMemory(pBlob->GetBufferPointer(), pBlob->GetBufferSize(),  0, m_pDevice, &m_pEffect);
		if(FAILED(ret))
		{
			return false;
		}

		if(m_pEffect->IsValid() == FALSE)
		{
			m_pEffect->Release();
			m_pEffect = NULL;
			return false;
		}

		D3DX11_EFFECT_DESC desc;

		if(FAILED(m_pEffect->GetDesc(&desc)))
		{
			m_pEffect->Release();
			m_pEffect = NULL;
			return false;
		}


		for(UINT i = 0; i < desc.Techniques; ++i)
		{
			ID3DX11EffectTechnique* pTech = m_pEffect->GetTechniqueByIndex(i);

			if(TRUE == pTech->IsValid())
			{
				m_pTech = pTech;
				break;
			}
		}

		if(m_pTech == NULL)
		{
			m_pEffect->Release();
			m_pEffect = NULL;
			m_pTech = NULL;
			return false;
		}

		D3DX11_TECHNIQUE_DESC tech;

		if(FAILED(m_pTech->GetDesc(&tech)))
		{
			m_pEffect->Release();
			m_pEffect = NULL;
			m_pTech = NULL;
		}
		m_nPass = tech.Passes;


		m_semantics.m_pViewTM					= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_VIEW");
		m_semantics.m_pWorldTM					= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_WORLD");
		m_semantics.m_pProjTM					= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_PROJ");

		m_semantics.m_pInvViewTM				= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_VIEW");
		m_semantics.m_pInvWorldTM				= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_WORLD");
		m_semantics.m_pInvProjTM				= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_PROJ");

		m_semantics.m_pWVTM						= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_WV");
		m_semantics.m_pWVPTM					= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_WVP");

		m_semantics.m_pInvWVTM					= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_WV");
		m_semantics.m_pInvWVPTM					= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_WVP");
		m_semantics.m_pInvVPTM					= (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_VP");


		m_semantics.m_pGBuffer					= (ID3DX11EffectShaderResourceVariable*)m_pEffect->GetVariableBySemantic("DR_GBUFFER");
		m_semantics.m_pABuffer					= (ID3DX11EffectShaderResourceVariable*)m_pEffect->GetVariableBySemantic("DR_ABUFFER");
		return true;
	}
void TerrainEffect::init(ID3D11Device* graphicsDevice, const char* path)
{
	ID3DBlob* errorBlob;
	ID3DBlob* effectBlob;

	#if defined(DEBUG) | defined(_DEBUG)
		unsigned flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS;
	#else
		unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
	#endif

	HRESULT hr = D3DX11CompileFromFileA(path, 0, 0, 0, "fx_5_0", flags, 0, 0, &effectBlob, &errorBlob, 0);

	if (hr != S_OK)
	{
		OutputDebugStringA((char*)errorBlob->GetBufferPointer());
		throw std::exception();
	}

	D3DX11CreateEffectFromMemory(effectBlob->GetBufferPointer(), effectBlob->GetBufferSize(), 0, graphicsDevice, &effect);

	effectBlob->Release();

	ID3DX11EffectTechnique* technique;
	
	technique = effect->GetTechniqueByIndex(0);
	effectPass = technique->GetPassByIndex(0);

	D3DX11_PASS_SHADER_DESC vertexShaderDesc;
	D3DX11_EFFECT_SHADER_DESC effectShaderDesc;
	
	effectPass->GetVertexShaderDesc(&vertexShaderDesc);

	vertexShaderDesc.pShaderVariable->GetShaderDesc(vertexShaderDesc.ShaderIndex, &effectShaderDesc);

	graphicsDevice->CreateInputLayout(TerrainPatch::inputElementDesc, TerrainPatch::numElements, effectShaderDesc.pBytecode, effectShaderDesc.BytecodeLength, &inputLayout);

	colormap = effect->GetVariableByName("Colormap")->AsShaderResource();
	heightmap = effect->GetVariableByName("Heightmap")->AsShaderResource();
	normalmap = effect->GetVariableByName("Normalmap")->AsShaderResource();
	colormaps = effect->GetVariableByName("Colormaps")->AsShaderResource();
	infomap = effect->GetVariableByName("Infomap")->AsShaderResource();
	slopemap = effect->GetVariableByName("Slopemap")->AsShaderResource();
	roughnessmap = effect->GetVariableByName("Roughnessmap")->AsShaderResource();

	fakeView = effect->GetVariableByName("FakeView")->AsMatrix();

	world = effect->GetVariableByName("World")->AsMatrix();
	view = effect->GetVariableByName("View")->AsMatrix();
	projection = effect->GetVariableByName("Projection")->AsMatrix();

	worldViewProjection = effect->GetVariableByName("WorldViewProjection")->AsMatrix();

	terrainSize = effect->GetVariableByName("TerrainSize")->AsScalar();
	terrainScale = effect->GetVariableByName("TerrainScale")->AsScalar();
	minPatchSize = effect->GetVariableByName("MinPatchSize")->AsScalar();
	minNodeSize = effect->GetVariableByName("MinNodeSize")->AsScalar();

	bumpiness = effect->GetVariableByName("Bumpiness")->AsScalar();
	roughnessModificator = effect->GetVariableByName("RoughnessModificator")->AsScalar();
	minPixelPerTriangle = effect->GetVariableByName("MinPixelPerTriangle")->AsScalar();
	colormapRepeat = effect->GetVariableByName("ColormapRepeat")->AsScalar();

	screenSize = effect->GetVariableByName("ScreenSize")->AsVector();
	slopeRange = effect->GetVariableByName("SlopeRange")->AsVector();

	colormapEnabled = effect->GetVariableByName("ColormapEnabled")->AsScalar();
	frustumCullingEnabled = effect->GetVariableByName("FrustumCullingEnabled")->AsScalar();
	heightTextureEnabled = effect->GetVariableByName("HeightTextureEnabled")->AsScalar();
	slopeTextureEnabled = effect->GetVariableByName("SlopeTextureEnabled")->AsScalar();
	lightingEnabled = effect->GetVariableByName("LightingEnabled")->AsScalar();
	roughnessEnabled = effect->GetVariableByName("RoughnessEnabled")->AsScalar();
	antiShimmeringEnabled = effect->GetVariableByName("AntiShimmeringEnabled")->AsScalar();
	showNodesEnabled = effect->GetVariableByName("ShowNodesEnabled")->AsScalar();
	bruteForceEnabled = effect->GetVariableByName("BruteForceEnabled")->AsScalar();
}
Beispiel #15
0
VoxelRenderer::VoxelRenderer(GraphicsDevice& graphicsDevice)
: m_graphicsDevice(graphicsDevice)
{
    if (!m_sharedWeakPtr.expired())
    {
        m_shared = m_sharedWeakPtr.lock();
    }
    else
    {
        m_shared = std::make_shared<SharedProperties>();
        m_sharedWeakPtr = std::weak_ptr<SharedProperties>(m_shared);

        //
        //  Create the vertex shader and input layout.
        //
        boost::intrusive_ptr<ID3D10Blob> bytecode, errors;
        D3DCHECK(D3DX11CompileFromFileA("assets/shaders/voxel_mesh_vs.hlsl",//  pSrcFile
                                        NULL,                               //  pDefines
                                        NULL,                               //  pInclude
                                        "main",                             //  pFunctionName
                                        "vs_4_0",                           //  pProfile
                                        0,                                  //  Flags1
                                        0,                                  //  Flags2
                                        NULL,                               //  pPump
                                        AttachPtr(bytecode),                //  ppShader
                                        AttachPtr(errors),                  //  ppErrorMsgs
                                        NULL));                             //  pHResult
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateVertexShader(
                                        bytecode->GetBufferPointer(),
                                        bytecode->GetBufferSize(),
                                        NULL,
                                        AttachPtr(m_shared->vertexShader)));
        
        D3D11_INPUT_ELEMENT_DESC inputElements[] =
        {
            {
                "POSITION",                                                 //  SemanticName
                0,                                                          //  SemanticIndex
                DXGI_FORMAT_R32G32B32_FLOAT,                                //  Format
                0,                                                          //  InputSlot
                0,                                                          //  AlignedByteOffset
                D3D11_INPUT_PER_VERTEX_DATA,                                //  InputSlotClass
                0                                                           //  InstanceDataStepRate
            },
            {
                "NORMAL",                                                   //  SemanticName
                0,                                                          //  SemanticIndex
                DXGI_FORMAT_R32_UINT,                                       //  Format
                0,                                                          //  InputSlot
                12,                                                         //  AlignedByteOffset
                D3D11_INPUT_PER_VERTEX_DATA,                                //  InputSlotClass
                0                                                           //  InstanceDataStepRate
            },
            {
                "TEXCOORD",                                                 //  SemanticName
                0,                                                          //  SemanticIndex
                DXGI_FORMAT_R32G32_UINT,                                    //  Format
                0,                                                          //  InputSlot
                16,                                                         //  AlignedByteOffset
                D3D11_INPUT_PER_VERTEX_DATA,                                //  InputSlotClass
                0                                                           //  InstanceDataStepRate
            }
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateInputLayout(
                                        inputElements,
                                        sizeof(inputElements) / sizeof(inputElements[0]),
                                        bytecode->GetBufferPointer(),
                                        bytecode->GetBufferSize(),
                                        AttachPtr(m_shared->inputLayout)));

        //
        //  Create the pixel shader.
        //
        D3DCHECK(D3DX11CompileFromFileA("assets/shaders/voxel_mesh_ps.hlsl",//  pSrcFile
                                        NULL,                               //  pDefines
                                        NULL,                               //  pInclude
                                        "main",                             //  pFunctionName
                                        "ps_4_0",                           //  pProfile
                                        0,                                  //  Flags1
                                        0,                                  //  Flags2
                                        NULL,                               //  pPump
                                        AttachPtr(bytecode),                //  ppShader
                                        AttachPtr(errors),                  //  ppErrorMsgs
                                        NULL));                             //  pHResult
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreatePixelShader(
                                        bytecode->GetBufferPointer(),
                                        bytecode->GetBufferSize(),
                                        NULL,
                                        AttachPtr(m_shared->pixelShader)));
    

        //
        //  Create the state objects.
        //
        D3D11_DEPTH_STENCIL_DESC depthStencilDesc = 
        {
            TRUE,                                                           //  DepthEnable
            D3D11_DEPTH_WRITE_MASK_ALL,                                     //  DepthWriteMask
            D3D11_COMPARISON_LESS,                                          //  ComparisonFunc
            TRUE,                                                           //  StencilEnable
            0,                                                              //  StencilReadMask
            0xFF,                                                           //  StencilWriteMask
            {                                                               //  FrontFace
                D3D11_STENCIL_OP_KEEP,                                      //      StencilFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilDepthFailOp
                D3D11_STENCIL_OP_INCR_SAT,                                  //      StencilPassOp
                D3D11_COMPARISON_ALWAYS,                                    //      StencilFunc
            },
            {                                                               //  BackFace
                D3D11_STENCIL_OP_KEEP,                                      //      StencilFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilDepthFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilPassOp
                D3D11_COMPARISON_NEVER,                                     //      StencilFunc
            }
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateDepthStencilState(
                                        &depthStencilDesc,
                                        AttachPtr(m_shared->depthStencilState)));

        D3D11_DEPTH_STENCIL_DESC transparentDepthStencilDesc = 
        {
            TRUE,                                                           //  DepthEnable
            D3D11_DEPTH_WRITE_MASK_ZERO,                                    //  DepthWriteMask
            D3D11_COMPARISON_LESS,                                          //  ComparisonFunc
            FALSE,                                                          //  StencilEnable
            0,                                                              //  StencilReadMask
            0,                                                              //  StencilWriteMask
            {                                                               //  FrontFace
                D3D11_STENCIL_OP_KEEP,                                      //      StencilFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilDepthFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilPassOp
                D3D11_COMPARISON_ALWAYS,                                    //      StencilFunc
            },
            {                                                               //  BackFace
                D3D11_STENCIL_OP_KEEP,                                      //      StencilFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilDepthFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilPassOp
                D3D11_COMPARISON_NEVER,                                     //      StencilFunc
            }
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateDepthStencilState(
                                        &depthStencilDesc,
                                        AttachPtr(m_shared->transparentDepthStencilState)));

        D3D11_DEPTH_STENCIL_DESC fillGapsDepthStencilDesc =
        {
            TRUE,                                                           //  DepthEnable
            D3D11_DEPTH_WRITE_MASK_ALL,                                     //  DepthWriteMask
            D3D11_COMPARISON_LESS,                                          //  ComparisonFunc
            TRUE,                                                           //  StencilEnable
            0xFF,                                                           //  StencilReadMask
            0,                                                              //  StencilWriteMask
            {                                                               //  FrontFace
                D3D11_STENCIL_OP_KEEP,                                      //      StencilFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilDepthFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilPassOp
                D3D11_COMPARISON_EQUAL                                      //      StencilFunc
            },
            {                                                               //  BackFace
                D3D11_STENCIL_OP_KEEP,                                      //      StencilFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilDepthFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilPassOp
                D3D11_COMPARISON_NEVER                                      //      StencilFunc
            }
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateDepthStencilState(&fillGapsDepthStencilDesc,
                                                                         AttachPtr(m_shared->fillGapsDepthStencilState)));


        D3D11_BLEND_DESC blendDesc =
        {
            FALSE,                                                           //  AlphaToCoverageEnable
            FALSE,                                                          //  IndependentBlendEnable
            {{                                                              //  RenderTarget[0]
                TRUE,                                                       //      BlendEnable
                D3D11_BLEND_SRC_ALPHA,                                      //      SrcBlend
                D3D11_BLEND_INV_SRC_ALPHA,                                  //      DestBlend
                D3D11_BLEND_OP_ADD,                                         //      BlendOp
                D3D11_BLEND_ZERO,                                           //      SrcBlendAlpha
                D3D11_BLEND_ZERO,                                           //      DestBlendAlpha
                D3D11_BLEND_OP_ADD,                                         //      BlendOpAlpha
                D3D11_COLOR_WRITE_ENABLE_ALL                                //      RenderTargetWriteMask
            }}
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateBlendState(&blendDesc,
                                                                  AttachPtr(m_shared->blendState)));
        //
        //  Load the textures.
        //
        const char* paths[] =
        {
            "assets/textures/rock.jpg",
            "assets/textures/dark_grass.png",
            "assets/textures/Grass_1.png",
            "assets/textures/dirt.jpg",
            "assets/textures/pjrock21.jpg",
            "assets/textures/darkrock.png",
            "assets/textures/sand.png"
        };
        for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++)
        {
            D3DCHECK(D3DX11CreateShaderResourceViewFromFileA(&m_graphicsDevice.GetD3DDevice(),
                                                             paths[i],
                                                             NULL,
                                                             NULL,
                                                             AttachPtr(m_shared->textureViews[i]),
                                                             NULL));
        }

        //
        //  Create the sampler state.
        //
        D3D11_SAMPLER_DESC samplerDesc =
        {
            D3D11_FILTER_MIN_MAG_MIP_LINEAR,                                //  Filter
            D3D11_TEXTURE_ADDRESS_WRAP,                                     //  AddressU
            D3D11_TEXTURE_ADDRESS_WRAP,                                     //  AddressV
            D3D11_TEXTURE_ADDRESS_WRAP,                                     //  AddressW
            0.0f,                                                           //  MaxLODBias
            0,                                                              //  MaxAnisotropy
            D3D11_COMPARISON_ALWAYS,                                        //  ComparisonFunc
            {0, 0, 0, 0},                                                   //  BorderColor
            -FLT_MAX,                                                       //  MinLOD
            FLT_MAX                                                         //  MaxLOD
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateSamplerState(&samplerDesc,
                                                                    AttachPtr(m_shared->samplerState)));
    }

    //
    //  Create the constant buffer.
    //
    D3D11_BUFFER_DESC constantBufferDesc =
    {
        sizeof(ShaderConstants),                                            //  ByteWidth
        D3D11_USAGE_DYNAMIC,                                                //  Usage
        D3D11_BIND_CONSTANT_BUFFER,                                         //  BindFlags
        D3D11_CPU_ACCESS_WRITE,                                             //  CPUAccessFlags
        0,                                                                  //  MiscFlags
        0                                                                   //  StructureByteSize
    };
    D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateBuffer(
                                        &constantBufferDesc,
                                        NULL,
                                        AttachPtr(m_constantBuffer)));
}
Beispiel #16
0
SkyRenderer::SkyRenderer(GraphicsDevice& graphicsDevice)
: m_graphicsDevice(graphicsDevice)
{
    if (!m_sharedWeakPtr.expired())
    {
        m_shared = m_sharedWeakPtr.lock();
    }
    else
    {
        m_shared = std::make_shared<SharedProperties>();
        m_sharedWeakPtr = std::weak_ptr<SharedProperties>(m_shared);
    
        //
        //  Create the vertex shader and input layout.
        //
        boost::intrusive_ptr<ID3D10Blob> bytecode, errors;
        D3DCHECK(D3DX11CompileFromFileA("assets/shaders/skybox_vs.hlsl",    //  pSrcFile
                                        NULL,                               //  pDefines
                                        NULL,                               //  pInclude
                                        "main",                             //  pFunctionName
                                        "vs_4_0",                           //  pProfile
                                        0,                                  //  Flags1
                                        0,                                  //  Flags2
                                        NULL,                               //  pPump
                                        AttachPtr(bytecode),                //  ppShader
                                        AttachPtr(errors),                  //  ppErrorMsgs
                                        NULL));                             //  pHResult
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateVertexShader(
                                        bytecode->GetBufferPointer(),
                                        bytecode->GetBufferSize(),
                                        NULL,
                                        AttachPtr(m_shared->vertexShader)));
        
        D3D11_INPUT_ELEMENT_DESC inputElements[] =
        {
            {
                "POSITION",                                                 //  SemanticName
                0,                                                          //  SemanticIndex
                DXGI_FORMAT_R32G32B32_FLOAT,                                //  Format
                0,                                                          //  InputSlot
                0,                                                          //  AlignedByteOffset
                D3D11_INPUT_PER_VERTEX_DATA,                                //  InputSlotClass
                0                                                           //  InstanceDataStepRate
            },
            {
                "TEXCOORD",                                                 //  SemanticName
                0,                                                          //  SemanticIndex
                DXGI_FORMAT_R32G32_FLOAT,                                   //  Format
                0,                                                          //  InputSlot
                12,                                                         //  AlignedByteOffset
                D3D11_INPUT_PER_VERTEX_DATA,                                //  InputSlotClass
                0                                                           //  InstanceDataStepRate
            }
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateInputLayout(
                                        inputElements,
                                        sizeof(inputElements) / sizeof(inputElements[0]),
                                        bytecode->GetBufferPointer(),
                                        bytecode->GetBufferSize(),
                                        AttachPtr(m_shared->inputLayout)));     

        //
        //  Create the pixel shader.
        //
        D3DCHECK(D3DX11CompileFromFileA("assets/shaders/skybox_ps.hlsl",    //  pSrcFile
                                        NULL,                               //  pDefines
                                        NULL,                               //  pInclude
                                        "main",                             //  pFunctionName
                                        "ps_4_0",                           //  pProfile
                                        0,                                  //  Flags1
                                        0,                                  //  Flags2
                                        NULL,                               //  pPump
                                        AttachPtr(bytecode),                //  ppShader
                                        AttachPtr(errors),                  //  ppErrorMsgs
                                        NULL));                             //  pHResult
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreatePixelShader(
                                        bytecode->GetBufferPointer(),
                                        bytecode->GetBufferSize(),
                                        NULL,
                                        AttachPtr(m_shared->pixelShader)));  

        //
        //  Create the renderer state objects.
        //
        D3D11_RASTERIZER_DESC rasterizerDesc =
        {
            D3D11_FILL_SOLID,                                               //  FillMode
            D3D11_CULL_NONE,                                                //  CullMode
            FALSE,                                                          //  FrontCounterClockwise
            0,                                                              //  DepthBias
            0.0f,                                                           //  DepthBiasClamp
            0.0f,                                                           //  SlopeScaledDepthBias
            FALSE,                                                          //  DepthClipEnable
            FALSE,                                                          //  ScissorEnable
            FALSE,                                                          //  MultisampleEnable
            FALSE                                                           //  AntialiasedLineEnable
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateRasterizerState(
                                        &rasterizerDesc,
                                        AttachPtr(m_shared->rasterizerState)));

        D3D11_DEPTH_STENCIL_DESC depthStencilDesc = 
        {
            TRUE,                                                           //  DepthEnable
            D3D11_DEPTH_WRITE_MASK_ZERO,                                    //  DepthWriteMask
            D3D11_COMPARISON_LESS_EQUAL,                                    //  ComparisonFunc
            FALSE,                                                          //  StencilEnable
            0,                                                              //  StencilReadMask
            0,                                                              //  StencilWriteMask
            {                                                               //  FrontFace
                D3D11_STENCIL_OP_KEEP,                                      //      StencilFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilDepthFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilPassOp
                D3D11_COMPARISON_NEVER,                                     //      StencilFunc
            },
            {                                                               //  BackFace
                D3D11_STENCIL_OP_KEEP,                                      //      StencilFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilDepthFailOp
                D3D11_STENCIL_OP_KEEP,                                      //      StencilPassOp
                D3D11_COMPARISON_NEVER,                                     //      StencilFunc
            }
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateDepthStencilState(
                                        &depthStencilDesc,
                                        AttachPtr(m_shared->depthStencilState)));

        //
        //  Create the vertex and index buffers.
        //
        D3D11_SUBRESOURCE_DATA vertexBufferData =
        {
            SkyboxVertices,                                                 //  pSysMem
            0,                                                              //  SysMemPitch
            0                                                               //  SysMemSlicePitch
        };
        D3D11_BUFFER_DESC vertexBufferDesc =
        {
            sizeof(SkyboxVertices),                                         //  ByteWidth
            D3D11_USAGE_IMMUTABLE,                                          //  Usage
            D3D11_BIND_VERTEX_BUFFER,                                       //  BindFlags
            0,                                                              //  CPUAccessFlags
            0,                                                              //  MiscFlags
            0                                                               //  StructureByteStride
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateBuffer(&vertexBufferDesc,
                                                              &vertexBufferData,
                                                              AttachPtr(m_shared->vertexBuffer)));

        D3D11_SUBRESOURCE_DATA indexBufferData =
        {
            SkyboxIndices,                                                  //  pSysMem
            0,                                                              //  SysMemPitch
            0                                                               //  SysMemSlicePitch
        };
        D3D11_BUFFER_DESC indexBufferDesc =
        {
            sizeof(SkyboxIndices),                                          //  ByteWidth
            D3D11_USAGE_IMMUTABLE,                                          //  Usage
            D3D11_BIND_INDEX_BUFFER,                                        //  BindFlags
            0,                                                              //  CPUAccessFlags
            0,                                                              //  MiscFlags
            0                                                               //  StructureByteStride
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateBuffer(&indexBufferDesc,
                                                              &indexBufferData,
                                                              AttachPtr(m_shared->indexBuffer)));

        //
        //  Load the sky texture.
        //
        D3DCHECK(D3DX11CreateShaderResourceViewFromFileA(&m_graphicsDevice.GetD3DDevice(),
                                                         "assets/textures/sky.jpg",
                                                         NULL,
                                                         NULL,
                                                         AttachPtr(m_shared->skyTextureView),
                                                         NULL));

        //
        //  Create the sampler state.
        //
        D3D11_SAMPLER_DESC samplerDesc =
        {
            D3D11_FILTER_MIN_MAG_MIP_LINEAR,                                //  Filter
            D3D11_TEXTURE_ADDRESS_CLAMP,                                     //  AddressU
            D3D11_TEXTURE_ADDRESS_CLAMP,                                     //  AddressV
            D3D11_TEXTURE_ADDRESS_CLAMP,                                     //  AddressW
            0.0f,                                                           //  MaxLODBias
            0,                                                              //  MaxAnisotropy
            D3D11_COMPARISON_ALWAYS,                                        //  ComparisonFunc
            {0, 0, 0, 0},                                                   //  BorderColor
            -FLT_MAX,                                                       //  MinLOD
            FLT_MAX                                                         //  MaxLOD
        };
        D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateSamplerState(&samplerDesc,
                                                                    AttachPtr(m_shared->samplerState)));                                                        
    }

    //
    //  Create the constant buffer.
    //
    D3D11_BUFFER_DESC constantBufferDesc =
    {
        sizeof(ShaderConstants),                                            //  ByteWidth
        D3D11_USAGE_DYNAMIC,                                                //  Usage
        D3D11_BIND_CONSTANT_BUFFER,                                         //  BindFlags
        D3D11_CPU_ACCESS_WRITE,                                             //  CPUAccessFlags
        0,                                                                  //  MiscFlags
        0                                                                   //  StructureByteSize
    };
    D3DCHECK(m_graphicsDevice.GetD3DDevice().CreateBuffer(
                                        &constantBufferDesc,
                                        NULL,
                                        AttachPtr(m_constantBuffer)));
}
void ComplexTree::init(ID3D11Device* device)
{
	ID3D11DeviceContext* deviceContext;
	device->GetImmediateContext(&deviceContext);

	HRESULT result = trunkMesh.Create(device, trunkPath, true);

	boundingBoxCenter = trunkMesh.GetMeshBBoxCenter(0);
	boundingBoxExtents = trunkMesh.GetMeshBBoxExtents(0);

	ID3DBlob* errorBlob;
	ID3DBlob* shaderBlob;

	result = D3DX11CompileFromFileA("Content/Effects/Trunk.fx", 0, 0, 0, "fx_5_0", 0, 0, 0, &shaderBlob, &errorBlob, 0);

	char* errorBuffer;
	if(errorBlob)
	{
		errorBuffer = (char*)errorBlob->GetBufferPointer();
	}

	result = D3DX11CreateEffectFromMemory(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), 0, device, &effect);
	
	if(shaderBlob)
		shaderBlob->Release();
	if(errorBlob)
		errorBlob->Release();

	for(int i = 0; i < TREE_INSTANCE_COUNT; ++i)
	{
		treePositions[i].x = (rand() / (float)RAND_MAX) * TREE_BORDER - TREE_BORDER / 2.0f;
		treePositions[i].y = 0;
		treePositions[i].z = (rand() / (float)RAND_MAX) * TREE_BORDER - TREE_BORDER / 2.0f;
	}

	D3D11_BUFFER_DESC instanceBufferDesc;
	ZeroMemory(&instanceBufferDesc, sizeof(D3D11_BUFFER_DESC));

	instanceBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	instanceBufferDesc.ByteWidth = sizeof(treePositions);
	instanceBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	instanceBufferDesc.CPUAccessFlags = 0;

	D3D11_SUBRESOURCE_DATA instanceData;
	ZeroMemory(&instanceData, sizeof(D3D11_SUBRESOURCE_DATA));
	instanceData.pSysMem = treePositions;

	device->CreateBuffer(&instanceBufferDesc, &instanceData, &instanceBuffer);

	technique = effect->GetTechniqueByName("Trunk");
	techniqueLOD1 = effect->GetTechniqueByName("TrunkLOD1");
	pass = technique->GetPassByIndex(0);
	passLOD1 = techniqueLOD1->GetPassByIndex(0);

	D3D11_INPUT_ELEMENT_DESC inputElementDescLOD0[] =
	{
		{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"TEXCOORD", 1, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1}
	};

	int inputElementCount = sizeof(inputElementDescLOD0) / sizeof(D3D11_INPUT_ELEMENT_DESC);

	D3DX11_PASS_DESC passDesc;
	pass->GetDesc(&passDesc);
	result = device->CreateInputLayout(inputElementDescLOD0, inputElementCount,
		passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &inputLayout);

	D3D11_INPUT_ELEMENT_DESC inputElementDescLOD1[] =
	{
		{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}
	};

	inputElementCount = sizeof(inputElementDescLOD1) / sizeof(D3D11_INPUT_ELEMENT_DESC);

	passLOD1->GetDesc(&passDesc);
	device->CreateInputLayout(inputElementDescLOD1, inputElementCount,
		passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &inputLayoutLOD1);

	CDXUTResourceCache& resourceCache = DXUTGetGlobalResourceCache();
	resourceCache.CreateTextureFromFile(device, deviceContext, L"Content/Textures/Trees/rinde_bumpmap.dds", &bumpMap);
	resourceCache.CreateTextureFromFile(device, deviceContext, L"Content/Textures/Trees/rinde.dds", &alternativeTrunkTexture);
	resourceCache.CreateTextureFromFile(device, deviceContext, L"Content/Textures/Trees/trunk414_normalmap.dds", &normalMap);
	resourceCache.CreateTextureFromFile(device, deviceContext, L"Content/Textures/Trees/trunk414_front.dds", &billboardFront);
	resourceCache.CreateTextureFromFile(device, deviceContext, L"Content/Textures/Trees/trunk414_side.dds", &billboardSide);
	resourceCache.CreateTextureFromFile(device, deviceContext, L"Content/Textures/Trees/trunk414_top.dds", &billboardTop);

	evViewProjection = effect->GetVariableByName("ViewProjection")->AsMatrix();
	evWorld = effect->GetVariableByName("World")->AsMatrix();
	evTrunkTexture = effect->GetVariableByName("TrunkTexture")->AsShaderResource();
	evBumpMap = effect->GetVariableByName("BumpMapTexture")->AsShaderResource();
	evNormalMap = effect->GetVariableByName("NormalMapTexture")->AsShaderResource();
	evBillboardTop = effect->GetVariableByName("BillboardTop")->AsShaderResource();
	evBillboardSide = effect->GetVariableByName("BillboardSide")->AsShaderResource();
	evBillboardFront = effect->GetVariableByName("BillboardFront")->AsShaderResource();
	evEdgeFactor = effect->GetVariableByName("EdgeFactor")->AsScalar();
	evInsideFactor = effect->GetVariableByName("InsideFactor")->AsScalar();
	evMinDistance = effect->GetVariableByName("MinDistance")->AsScalar();
	evMaxDistance = effect->GetVariableByName("MaxDistance")->AsScalar();
	evBoundingBoxCenter = effect->GetVariableByName("BoundingBoxCenter")->AsScalar();
	evBoundingBoxExtents = effect->GetVariableByName("BoundingBoxExtents")->AsScalar();
	evGSCulling = effect->GetVariableByName("GSCulling")->AsScalar();
	evShowSavedCulling = effect->GetVariableByName("ShowSavedCulling")->AsScalar();
	evSavedViewProjection = effect->GetVariableByName("SavedViewProjection")->AsMatrix();

	evCameraPosition = effect->GetVariableByName("CameraPosition")->AsVector();
	evLightVector = effect->GetVariableByName("LightVector")->AsVector();
	evAmbientLight = effect->GetVariableByName("AmbientLight")->AsVector();
	evDiffuseLight = effect->GetVariableByName("DiffuseLight")->AsVector();
	evSpecularLight = effect->GetVariableByName("SpecularLight")->AsVector();
	evShininess = effect->GetVariableByName("Shininess")->AsScalar();

	evBumpMap->SetResource(bumpMap);
	evTrunkTexture->SetResource(alternativeTrunkTexture);
	evNormalMap->SetResource(normalMap);
	evBillboardTop->SetResource(billboardTop);
	evBillboardFront->SetResource(billboardFront);
	evBillboardSide->SetResource(billboardSide);
	evEdgeFactor->SetFloat(TREE_TESSELLATION_FACTOR_EDGES);
	evInsideFactor->SetFloat(TREE_TESSELLATION_FACTOR_INSIDE);
	evMinDistance->SetFloat(TREE_MIN_DISTANCE);
	evMaxDistance->SetFloat(TREE_MAX_DISTANCE);
	evBoundingBoxCenter->SetFloatArray(boundingBoxCenter, 0, 3);
	evBoundingBoxExtents->SetFloatArray(boundingBoxExtents, 0, 3);

	deviceContext->Release();
}
Beispiel #18
0
bool Effect::Compile(char* pFilename, char* pEntryPoint, ShaderTarget target, bool model5)
{
	char* model;

	switch(target)
	{
	case Target_VertexShader:
		if(model5)
			model="vs_5_0";
		else
			model="vs_4_0";
		break;

	case Target_PixelShader:
		if(model5)
			model="ps_5_0";
		else
			model="ps_4_0";
		break;

	case Target_GeometryShader:
		if(model5)
			model="gs_5_0";
		else
			model="gs_4_0";	
		break;
		
	case Target_HullShader:
		if(model5)
			model="hs_5_0";
		else
			model="hs_4_0";
		break;
		
	case Target_DomainShader:
		if(model5)
			model="ds_5_0";
		else
			model="ds_4_0";
		break;
	}

	ID3DBlob* code;
	ID3DBlob* error;
	
	HR(D3DX11CompileFromFileA( pFilename, NULL, NULL, pEntryPoint, model, 0, 0, NULL, &code, &error,NULL));

	switch(target)
	{
	case Target_VertexShader:
		mpVertexByteCode = new byte[code->GetBufferSize()];
		mVertexByteSize = code->GetBufferSize();
		memcpy_s(mpVertexByteCode, code->GetBufferSize(), code->GetBufferPointer(), code->GetBufferSize());
		HR(mpDeviceManager->mpDevice->CreateVertexShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mpVertexShader) );
		break;

	case Target_PixelShader:
		HR(mpDeviceManager->mpDevice->CreatePixelShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mpPixelShader) );
		break;

	case Target_GeometryShader:
		HR (mpDeviceManager->mpDevice->CreateGeometryShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mpGeometryShader) );
		break;
		
	case Target_HullShader:
		HR (mpDeviceManager->mpDevice->CreateHullShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mpHullShader) );
		break;
		
	case Target_DomainShader:
		HR (mpDeviceManager->mpDevice->CreateDomainShader(code->GetBufferPointer(), code->GetBufferSize(), NULL ,&mpDomainShader) );
		break;
	}

	SAFE_RELEASE(code);
	SAFE_RELEASE(error);

	return true;
}