Esempio n. 1
0
bool Shader::Compile(string &shaderCode)
{
    LPD3DXBUFFER error = nullptr;
    SOC_dword flags = 0;
    LPDIRECT3DDEVICE9 device = dynamic_cast<Device::Graphics*>(graphics)->GetD3DDevice();
    bool success = true;

#if _DEBUG
    flags |= D3DXSHADER_DEBUG;
#endif

    success = SUCCEEDED( D3DXCreateEffect(device, shaderCode.data(), shaderCode.length(), NULL, NULL, flags, NULL, &shader, &error) );

#if _DEBUG
    if(error)
    {
        int size = error->GetBufferSize();
        void *ack = error->GetBufferPointer();

        if(ack)
        {
            char *str = new char[size];
            memcpy(str, (const char*)ack, size);
            //					sprintf(str, (const char*)ack, size);
            OutputDebugString(str);
            delete[] str;
        }
    }
#endif
    compiled = success;
    if(success)
        GetRequiredParameters(&requiredMatrixParam, &requiredLightParam);

    return success;
}
Esempio n. 2
0
// ******************************************************************
// Erstellen aus einem String
age_Result ageD_D3DEffect::Init(char* pcCode,
						int iSize)
{
	HRESULT hResult;

	// Parameter prüfen und sicherstellen, dass Direct3D initialisiert wurde
	if(pcCode == NULL)					AGE_ERROR_NULL_POINTER("pcCode", AGE_ERROR);
	if(iSize == 0 || iSize < -1)		AGE_ERROR_INVALID_VALUE("iSize", AGE_ERROR);
	if(!ageG_Direct3D::IsInitialized())	AGE_ERROR("Direct3D wurde noch nicht initialisiert!", AGE_ERROR);


	// Länge anpassen
	if(iSize == -1) iSize = strlen(pcCode);

	// Jetzt den Effekt erstellen
	if(FAILED(hResult = D3DXCreateEffect(ageG_Direct3D::GetDevice(),
										 pcCode, iSize, NULL, NULL, 0,
										 age_g_pEffectPool, &m_pEffect, NULL)))
	{
		// Fehler!
		AGE_ERROR_DIRECTX("D3DXCreateEffect", hResult, AGE_ERROR);
	}

	// Effektbeschreibung abfragen
	m_pEffect->GetDesc(&m_Desc);

	// Die erste gültige Technik setzen
	SetTechnique(-1);

	return AGE_OK;
}
Esempio n. 3
0
    GameAsset* ShaderEffect::Create(StreamReader& reader, GameAsset* existingInstance)
    {
        GraphicsDevice* graphicsDevice = static_cast<GraphicsDevice*>(reader.ReadModule(GraphicsDevice::ClassID));
        
        reader.ReadInt(); // NOT USED

        const int codeLength = reader.ReadInt();
        byte* code = BBStackAlloc(byte, codeLength);
        reader.Read(code, codeLength);

        ID3DXEffect* handle = nullptr;
        ID3DXBuffer* errorBuffer = nullptr;
        HRESULT result = D3DXCreateEffect(graphicsDevice->GetD3DDevice(),
                                          code, codeLength,
                                          NULL, NULL, D3DXSHADER_OPTIMIZATION_LEVEL3, 0, &handle, &errorBuffer);
        if (result != D3D_OK)
        {
            Log::Error("ShaderEffect", Int::ToString(result).CStr());

            if (errorBuffer)
                Log::Error("ShaderEffect", reinterpret_cast<const char*>(errorBuffer->GetBufferPointer()));
        }

        if (existingInstance == nullptr)
            existingInstance = new ShaderEffect(graphicsDevice);

        static_cast<ShaderEffect*>(existingInstance)->Setup(handle);

        BBStackFree(code);

        return existingInstance;
    }
Esempio n. 4
0
bool Shader::CreateFromMemory( LPCVOID buffer,size_t size )
{
	Graphics* graphics = Graphics::GetInstance();

	if( m_pEffect )
	{
		m_pEffect.Release();
		graphics->DelResource( this );
	}

	LPD3DXBUFFER pBuffer = NULL;

	HRESULT hr = D3DXCreateEffect(
		graphics->GetDirect3DDevice(),
		buffer,
		size,
		NULL,NULL,0,NULL,&m_pEffect,&pBuffer );

	if( pBuffer )
	{
		tstring error = to_tstring( (char*)pBuffer->GetBufferPointer() );
		OutputDebugStringFormat( _T("effect compiled\n%s"),error.c_str() );

		pBuffer->Release();
	}

	if( hr!=D3D_OK )
	{
		return false;
	}

	graphics->AddResource( this );

	return true;
}
Esempio n. 5
0
CPixelBufferView::EffectPtr CPixelBufferView::CreateEffectFromResource(const TCHAR* resourceName)
{
	HRESULT result = S_OK;

	HRSRC shaderResourceInfo = FindResource(GetModuleHandle(nullptr), resourceName, _T("TEXTFILE"));
	assert(shaderResourceInfo != nullptr);

	HGLOBAL shaderResourceHandle = LoadResource(GetModuleHandle(nullptr), shaderResourceInfo);
	DWORD shaderResourceSize = SizeofResource(GetModuleHandle(nullptr), shaderResourceInfo);

	const char* shaderData = reinterpret_cast<const char*>(LockResource(shaderResourceHandle));

	EffectPtr effect;
	Framework::Win32::CComPtr<ID3DXBuffer> errors;
	result = D3DXCreateEffect(m_device, shaderData, shaderResourceSize, nullptr, nullptr, 0, nullptr, &effect, &errors);
	if(!errors.IsEmpty())
	{
		std::string errorText(reinterpret_cast<const char*>(errors->GetBufferPointer()), reinterpret_cast<const char*>(errors->GetBufferPointer()) + errors->GetBufferSize());
		OutputDebugStringA("Failed to compile shader:\r\n");
		OutputDebugStringA(errorText.c_str());
	}
	assert(SUCCEEDED(result));

	UnlockResource(shaderResourceHandle);

	return effect;
}
Esempio n. 6
0
//
// ShaderMeshNode::VOnRestore					- very similar to MeshNode::VOnRestore
//
HRESULT D3DShaderMeshNode9::VOnRestore(Scene *pScene)
{
	SAFE_RELEASE(m_pEffect);

	DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE | D3DXSHADER_DEBUG | D3DXSHADER_NO_PRESHADER;
	HRESULT hr;

    Resource resource(m_fxFileName);
    shared_ptr<ResHandle> pResourceHandle = g_pApp->m_ResCache->GetHandle(&resource);  // this actually loads the XML file from the zip file
	V ( D3DXCreateEffect( DXUTGetD3D9Device(), pResourceHandle->Buffer(), pResourceHandle->Size(), NULL, NULL, dwShaderFlags, NULL, &m_pEffect, NULL ) );
	return D3DMeshNode9::VOnRestore(pScene);
}
Esempio n. 7
0
/* Creates the shaders
 */
void D3DRenderer::CreateShaders()
{
	HRESULT hr;

	D3DVERTEXELEMENT9 dwDecl3[] =
	{
		{ 0, 0,  D3DDECLTYPE_FLOAT3,   		D3DDECLMETHOD_DEFAULT, 		D3DDECLUSAGE_POSITION,	0 },
		{ 0, 12, D3DDECLTYPE_FLOAT2,   		D3DDECLMETHOD_DEFAULT, 		D3DDECLUSAGE_TEXCOORD,	0 },
		{ 0, 20, D3DDECLTYPE_D3DCOLOR,   	D3DDECLMETHOD_DEFAULT, 		D3DDECLUSAGE_COLOR,		0 },
		D3DDECL_END()
	};  

	hr = mD3DDevice->CreateVertexDeclaration(dwDecl3, &mVertexDeclaration);  

	if( FAILED(hr) )
	{
		// TODO : Error reporting
	}


	LPD3DXBUFFER pBufferErrors = NULL;
	LPD3DXEFFECT pEffect = NULL;

	hr = D3DXCreateEffect(	mD3DDevice,
							g_Otter,
							sizeof(g_Otter),
							NULL, 
							NULL,
							D3DXSHADER_OPTIMIZATION_LEVEL3,
							NULL,
							&pEffect,
							&pBufferErrors);

	if( FAILED(hr) )
	{
		const char* errorString = (const char*)pBufferErrors->GetBufferPointer();	

		// TODO: Error reporting

		pBufferErrors->Release();
		pBufferErrors = NULL;
	}

	Shader shader;
	shader.mName = "Default";
	shader.mEffect = pEffect;

	mShaders[0] = shader;
}
Esempio n. 8
0
bool CD3D9Shader::createFromMemory(void* pBuf, int nSize,LPD3DXINCLUDE pInclude)
{
	IDirect3DDevice9* pD3D9Device = GetD3D9RenderSystem().GetD3D9Device();
	if (ms_pEffectPool==NULL)
	{
		D3DXCreateEffectPool( & ms_pEffectPool);
	}
	DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE;
	ID3DXBuffer* errorBuffer = 0;
	D3DXCreateEffect(pD3D9Device,pBuf,nSize, NULL, pInclude, dwShaderFlags, 
		ms_pEffectPool, &m_pEffect, &errorBuffer);
	// output any error messages
	if(errorBuffer)
	{
		::MessageBoxA(0, (char*)errorBuffer->GetBufferPointer(), 0, 0);
		S_REL(errorBuffer);
	}
	return m_pEffect!=NULL;
}
Esempio n. 9
0
int D3DRenderer::LoadShader(const char* szName, const char* szShader)
{
	std::string name = szName;
	ShaderMap::iterator it = mShaders.begin();
	for(; it != mShaders.end(); it++)
	{
		if((*it).second.mName == name)
			return (*it).first;
	}

	LPD3DXBUFFER pBufferErrors = NULL;
	Shader shader;
	shader.mName = name;
	shader.mSource = szShader;

	HRESULT hr = D3DXCreateEffect(	mD3DDevice,
									szShader,
									strlen(szShader) + 1,
									NULL, 
									NULL,
									D3DXSHADER_OPTIMIZATION_LEVEL3,
									NULL,
									&shader.mEffect,
									&pBufferErrors);

	if( FAILED(hr) )
	{
		const char* errorString = (const char*)pBufferErrors->GetBufferPointer();	

		// TODO: Error reporting

		pBufferErrors->Release();
		pBufferErrors = NULL;

		return 0;
	}

	mShaders[mNextShaderID] = shader;
	return mNextShaderID++;
}
Esempio n. 10
0
u32 Effect::load()
{
	LPD3DXBUFFER pBufferErrors = NULL;
	release();

	Buffer buffer;
	string g_path_effects = "shaders/";

	if(!gK.fs.load(g_path_effects+strFilename, buffer))return 0;

	if(FAILED(D3DXCreateEffect(gD.getDev(),buffer.data,buffer.size, NULL, NULL, 0, NULL, &lpEffect, &pBufferErrors )))
	{
		if(pBufferErrors)
		{
			LPVOID pCompilErrors = pBufferErrors->GetBufferPointer();
			gK.log.prn((char*)pCompilErrors);
		}
		pBufferErrors->Release();
		return 0;
	}
	return 1;
}
Esempio n. 11
0
//-----------------------------------------------------------------------------
// Name: InitDeviceObjects()
// Desc: Initialize scene objects.
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::InitDeviceObjects()
{
    // Load the file objects
    if( FAILED( m_pShinyTeapot->Create( m_pd3dDevice, _T("teapot.x") ) ) )
        return D3DAPPERR_MEDIANOTFOUND;
    if( FAILED( m_pSkyBox->Create( m_pd3dDevice, _T("lobby_skybox.x") ) ) )
        return D3DAPPERR_MEDIANOTFOUND;
    if( FAILED( D3DUtil_CreateTexture( m_pd3dDevice, _T("spheremap.bmp"), &m_pSphereMap ) ) )
        return D3DAPPERR_MEDIANOTFOUND;

    // Set mesh properties
    m_pShinyTeapot->SetFVF( m_pd3dDevice, D3DFVF_ENVMAPVERTEX );

    // Restore the device-dependent objects
    m_pFont->InitDeviceObjects( m_pd3dDevice );

    // Create Effect object
    if( FAILED( D3DXCreateEffect( m_pd3dDevice, g_szEffect, g_cchEffect, &m_pEffect, NULL ) ) )
        return E_FAIL;

    return S_OK;
}
Esempio n. 12
0
void* LcD3D_EffectStringBuild(PDEV pDev, char* sStr, int iLen)
{
	HRESULT	hr;

	DWORD dFlag = 0;
	#if defined( _DEBUG ) || defined( DEBUG )
	dFlag |= D3DXSHADER_DEBUG;
	#endif

	PDEF			pEft = NULL;
	LPD3DXBUFFER	pErr = NULL;

	hr = D3DXCreateEffect(	pDev
		,	sStr
		,	iLen
		,	NULL
		,	NULL
		,	dFlag
		,	NULL
		,	&pEft
		,	&pErr);

	if(FAILED(hr))
	{
		pEft	= NULL;

		if(pErr)
		{
			char* sErr = (char*)pErr->GetBufferPointer();
			LcD3D_GetDxError(hr, sErr);
			pErr->Release();
		}
		else
			LcD3D_GetDxError(hr);
	}

	return pEft;
}
Esempio n. 13
0
static void ResetDevice(bool CreateNew) {
	D3DPRESENT_PARAMETERS params;
	ZeroMemory(&params, sizeof(params));
	params.BackBufferCount=1;
	params.BackBufferFormat=(GraphicsMode==5)?D3DFMT_UNKNOWN:D3DFMT_X8R8G8B8;
	params.BackBufferWidth=gWidth;
	params.BackBufferHeight=gHeight;
	params.EnableAutoDepthStencil=false;
	params.MultiSampleQuality=0;
	params.MultiSampleType=D3DMULTISAMPLE_NONE;
	params.Windowed=(GraphicsMode==5);
	params.SwapEffect=D3DSWAPEFFECT_DISCARD;
	params.hDeviceWindow=window;
	params.PresentationInterval=D3DPRESENT_INTERVAL_IMMEDIATE;

	bool software=false;
	if(CreateNew) {
		if(FAILED(d3d9->CreateDevice(0,D3DDEVTYPE_HAL,window,D3DCREATE_PUREDEVICE|D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_MULTITHREADED|D3DCREATE_FPU_PRESERVE,&params,&d3d9Device))) {
			software=true;
			d3d9->CreateDevice(0,D3DDEVTYPE_HAL,window,D3DCREATE_SOFTWARE_VERTEXPROCESSING|D3DCREATE_MULTITHREADED|D3DCREATE_FPU_PRESERVE,&params,&d3d9Device);
		}
		D3DCAPS9 caps;
		d3d9Device->GetDeviceCaps(&caps);
		ShaderVersion=((caps.PixelShaderVersion&0x0000ff00)>>8)*10 + (caps.PixelShaderVersion&0xff);

		if(GPUBlt==2) {
			if(ShaderVersion<20) GPUBlt=0;
		}

		if(GPUBlt) {
			D3DXCreateEffect(d3d9Device, gpuEffect, strlen(gpuEffect), 0, 0, 0, 0, &gpuBltEffect, 0);
			gpuBltBuf=gpuBltEffect->GetParameterByName(0, "image");
			gpuBltPalette=gpuBltEffect->GetParameterByName(0, "palette");
			gpuBltHead=gpuBltEffect->GetParameterByName(0, "head");
			gpuBltHeadSize=gpuBltEffect->GetParameterByName(0, "size");
			gpuBltHeadCorner=gpuBltEffect->GetParameterByName(0, "corner");
		}
	} else {
Esempio n. 14
0
	bool Effect::loadFromMemory( const u8* data, u32 len )
	{
		DWORD dwFlag = 0;

		ID3DXBuffer *pError = NULL;
		HRESULT hr = D3DXCreateEffect(Paras::getInstancePtr()->_device, data, len, NULL, NULL, dwFlag, NULL, &_effect, &pError);
		if(FAILED(hr))
		{
			if(pError)
			{
				const char* szError = (const char*)pError->GetBufferPointer();
				std::ostringstream buf;
				buf<<"D3DXCreateEffect failed, reason:"<<szError;
				Error(buf.str());
			}
			else
			{
				Error("D3DXCreateEffect failed");
			}
			return false;
		}

		return true;
	}
Esempio n. 15
0
bool CDirect3D::SetShaderHLSL(const TCHAR *file)
{
	//MUDLORD: the guts
	//Compiles a shader from files on disc
	//Sets LUT textures to texture files in PNG format.

	TCHAR folder[MAX_PATH];
	TCHAR rubyLUTfileName[MAX_PATH];
	TCHAR *slash;
	char *shaderText = NULL;

	TCHAR errorMsg[MAX_PATH + 50];

	IXMLDOMDocument * pXMLDoc = NULL;
	IXMLDOMElement * pXDE = NULL;
	IXMLDOMNode * pXDN = NULL;
	BSTR queryString, nodeContent;

	HRESULT hr;

	shaderTimer = 1.0f;
	shaderTimeStart = 0;
	shaderTimeElapsed = 0;

	if(effect) {
		effect->Release();
		effect = NULL;
	}
	for(int i = 0; i < MAX_SHADER_TEXTURES; i++) {
		if (rubyLUT[i] != NULL) {
			rubyLUT[i]->Release();
			rubyLUT[i] = NULL;
		}
	}
	if (file == NULL || *file==TEXT('\0'))
		return true;

	hr = CoCreateInstance(CLSID_DOMDocument,NULL,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&pXMLDoc));

	if(FAILED(hr)) {
		MessageBox(NULL, TEXT("Error creating XML Parser"), TEXT("Shader Loading Error"),
			MB_OK|MB_ICONEXCLAMATION);
		return false;
	}

	VARIANT fileName;
	VARIANT_BOOL ret;
	fileName.vt = VT_BSTR;
#ifdef UNICODE
	fileName.bstrVal = SysAllocString(file);
#else
	wchar_t tempfilename[MAX_PATH];
	MultiByteToWideChar(CP_UTF8,0,file,-1,tempfilename,MAX_PATH);
	fileName.bstrVal = SysAllocString(tempfilename);
#endif
	hr = pXMLDoc->load(fileName,&ret);
	SysFreeString(fileName.bstrVal);

	if(FAILED(hr) || hr==S_FALSE) {
		_stprintf(errorMsg,TEXT("Error loading HLSL shader file:\n%s"),file);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK|MB_ICONEXCLAMATION);
		pXMLDoc->Release();
		return false;
	}

	VARIANT attributeValue;
	BSTR attributeName;

	hr = pXMLDoc->get_documentElement(&pXDE);
	if(FAILED(hr) || hr==S_FALSE) {
		_stprintf(errorMsg,TEXT("Error loading root element from file:\n%s"),file);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK|MB_ICONEXCLAMATION);
		pXMLDoc->Release();
		return false;
	}

	attributeName=SysAllocString(L"language");
	pXDE->getAttribute(attributeName,&attributeValue);
	SysFreeString(attributeName);
	pXDE->Release();

	if(attributeValue.vt!=VT_BSTR || lstrcmpiW(attributeValue.bstrVal,L"hlsl")) {
		_stprintf(errorMsg,TEXT("Shader language is <%s>, expected <HLSL> in file:\n%s"),attributeValue.bstrVal,file);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK|MB_ICONEXCLAMATION);
		if(attributeValue.vt==VT_BSTR) SysFreeString(attributeValue.bstrVal);
		pXMLDoc->Release();
		return false;
	}
	if(attributeValue.vt==VT_BSTR) SysFreeString(attributeValue.bstrVal);

	queryString=SysAllocString(L"/shader/source");
	hr = pXMLDoc->selectSingleNode(queryString,&pXDN);
	SysFreeString(queryString);

	if(hr == S_OK) {
		hr = pXDN->get_text(&nodeContent);
		if(hr == S_OK) {
			int requiredChars = WideCharToMultiByte(CP_ACP,0,nodeContent,-1,shaderText,0,NULL,NULL);
			shaderText = new char[requiredChars];
			WideCharToMultiByte(CP_UTF8,0,nodeContent,-1,shaderText,requiredChars,NULL,NULL);
		}
		SysFreeString(nodeContent);
		pXDN->Release();
		pXDN = NULL;
	}

	pXMLDoc->Release();

	if(!shaderText) {
		_stprintf(errorMsg,TEXT("No HLSL shader program in file:\n%s"),file);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"),
			MB_OK|MB_ICONEXCLAMATION);
		return false;
	}

	LPD3DXBUFFER pBufferErrors = NULL;
	hr = D3DXCreateEffect( pDevice,shaderText,strlen(shaderText),NULL, NULL,
		D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY, NULL, &effect, 
		&pBufferErrors );
	delete[] shaderText;
	if( FAILED(hr) ) {
		_stprintf(errorMsg,TEXT("Error parsing HLSL shader file:\n%s"),file);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK|MB_ICONEXCLAMATION);
		if(pBufferErrors) {
			LPVOID pCompilErrors = pBufferErrors->GetBufferPointer();
			MessageBox(NULL, (const TCHAR*)pCompilErrors, TEXT("FX Compile Error"),
				MB_OK|MB_ICONEXCLAMATION);
		}
		return false;
	}

	lstrcpy(folder,file);
	slash = _tcsrchr(folder,TEXT('\\'));
	if(slash)
		*(slash+1)=TEXT('\0');
	else
		*folder=TEXT('\0');
	SetCurrentDirectory(S9xGetDirectoryT(DEFAULT_DIR));

	for(int i = 0; i < MAX_SHADER_TEXTURES; i++) {		
		_stprintf(rubyLUTfileName, TEXT("%srubyLUT%d.png"), folder, i);
		hr = D3DXCreateTextureFromFile(pDevice,rubyLUTfileName,&rubyLUT[i]);
		if FAILED(hr){
			rubyLUT[i] = NULL;
		}
	}

	D3DXHANDLE hTech;
	effect->FindNextValidTechnique(NULL,&hTech);
	effect->SetTechnique( hTech );
	shader_type = D3D_SHADER_HLSL;
	return true;
}
Esempio n. 16
0
//-------------------------------------------------------------------------------
int CMaterialManager::CreateMaterial(
    AssetHelper::MeshHelper* pcMesh,const aiMesh* pcSource)
{
    ai_assert(NULL != pcMesh);
    ai_assert(NULL != pcSource);

    ID3DXBuffer* piBuffer;

    D3DXMACRO sMacro[64];

    // extract all properties from the ASSIMP material structure
    const aiMaterial* pcMat = g_pcAsset->pcScene->mMaterials[pcSource->mMaterialIndex];

    //
    // DIFFUSE COLOR --------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_DIFFUSE,
        (aiColor4D*)&pcMesh->vDiffuseColor))
    {
        pcMesh->vDiffuseColor.x = 1.0f;
        pcMesh->vDiffuseColor.y = 1.0f;
        pcMesh->vDiffuseColor.z = 1.0f;
        pcMesh->vDiffuseColor.w = 1.0f;
    }
    //
    // SPECULAR COLOR --------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_SPECULAR,
        (aiColor4D*)&pcMesh->vSpecularColor))
    {
        pcMesh->vSpecularColor.x = 1.0f;
        pcMesh->vSpecularColor.y = 1.0f;
        pcMesh->vSpecularColor.z = 1.0f;
        pcMesh->vSpecularColor.w = 1.0f;
    }
    //
    // AMBIENT COLOR --------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_AMBIENT,
        (aiColor4D*)&pcMesh->vAmbientColor))
    {
        pcMesh->vAmbientColor.x = 0.0f;
        pcMesh->vAmbientColor.y = 0.0f;
        pcMesh->vAmbientColor.z = 0.0f;
        pcMesh->vAmbientColor.w = 1.0f;
    }
    //
    // EMISSIVE COLOR -------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_EMISSIVE,
        (aiColor4D*)&pcMesh->vEmissiveColor))
    {
        pcMesh->vEmissiveColor.x = 0.0f;
        pcMesh->vEmissiveColor.y = 0.0f;
        pcMesh->vEmissiveColor.z = 0.0f;
        pcMesh->vEmissiveColor.w = 1.0f;
    }

    //
    // Opacity --------------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialFloat(pcMat,AI_MATKEY_OPACITY,&pcMesh->fOpacity))
    {
        pcMesh->fOpacity = 1.0f;
    }

    //
    // Shading Model --------------------------------------------------
    //
    bool bDefault = false;
    if(AI_SUCCESS != aiGetMaterialInteger(pcMat,AI_MATKEY_SHADING_MODEL,(int*)&pcMesh->eShadingMode ))
    {
        bDefault = true;
        pcMesh->eShadingMode = aiShadingMode_Gouraud;
    }


    //
    // Shininess ------------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialFloat(pcMat,AI_MATKEY_SHININESS,&pcMesh->fShininess))
    {
        // assume 15 as default shininess
        pcMesh->fShininess = 15.0f;
    }
    else if (bDefault)pcMesh->eShadingMode  = aiShadingMode_Phong;


    //
    // Shininess strength ------------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialFloat(pcMat,AI_MATKEY_SHININESS_STRENGTH,&pcMesh->fSpecularStrength))
    {
        // assume 1.0 as default shininess strength
        pcMesh->fSpecularStrength = 1.0f;
    }

    aiString szPath;

    aiTextureMapMode mapU(aiTextureMapMode_Wrap),mapV(aiTextureMapMode_Wrap);

    bool bib =false;
    if (pcSource->mTextureCoords[0])
    {

        //
        // DIFFUSE TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_DIFFUSE(0),&szPath))
        {
            LoadTexture(&pcMesh->piDiffuseTexture,&szPath);

            aiGetMaterialInteger(pcMat,AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0),(int*)&mapU);
            aiGetMaterialInteger(pcMat,AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0),(int*)&mapV);
        }

        //
        // SPECULAR TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_SPECULAR(0),&szPath))
        {
            LoadTexture(&pcMesh->piSpecularTexture,&szPath);
        }

        //
        // OPACITY TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_OPACITY(0),&szPath))
        {
            LoadTexture(&pcMesh->piOpacityTexture,&szPath);
        }
        else
        {
            int flags = 0;
            aiGetMaterialInteger(pcMat,AI_MATKEY_TEXFLAGS_DIFFUSE(0),&flags);

            // try to find out whether the diffuse texture has any
            // non-opaque pixels. If we find a few, use it as opacity texture
            if (pcMesh->piDiffuseTexture && !(flags & aiTextureFlags_IgnoreAlpha) && HasAlphaPixels(pcMesh->piDiffuseTexture))
            {
                int iVal;

                // NOTE: This special value is set by the tree view if the user
                // manually removes the alpha texture from the view ...
                if (AI_SUCCESS != aiGetMaterialInteger(pcMat,"no_a_from_d",0,0,&iVal))
                {
                    pcMesh->piOpacityTexture = pcMesh->piDiffuseTexture;
                    pcMesh->piOpacityTexture->AddRef();
                }
            }
        }

        //
        // AMBIENT TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_AMBIENT(0),&szPath))
        {
            LoadTexture(&pcMesh->piAmbientTexture,&szPath);
        }

        //
        // EMISSIVE TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_EMISSIVE(0),&szPath))
        {
            LoadTexture(&pcMesh->piEmissiveTexture,&szPath);
        }

        //
        // Shininess TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_SHININESS(0),&szPath))
        {
            LoadTexture(&pcMesh->piShininessTexture,&szPath);
        }

        //
        // Lightmap TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_LIGHTMAP(0),&szPath))
        {
            LoadTexture(&pcMesh->piLightmapTexture,&szPath);
        }


        //
        // NORMAL/HEIGHT MAP ------------------------------------------------
        //
        bool bHM = false;
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_NORMALS(0),&szPath))
        {
            LoadTexture(&pcMesh->piNormalTexture,&szPath);
        }
        else
        {
            if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_HEIGHT(0),&szPath))
            {
                LoadTexture(&pcMesh->piNormalTexture,&szPath);
            }
            else bib = true;
            bHM = true;
        }

        // normal/height maps are sometimes mixed up. Try to detect the type
        // of the texture automatically
        if (pcMesh->piNormalTexture)
        {
            HMtoNMIfNecessary(pcMesh->piNormalTexture, &pcMesh->piNormalTexture,bHM);
        }
    }

    // check whether a global background texture is contained
    // in this material. Some loaders set this value ...
    if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_GLOBAL_BACKGROUND_IMAGE,&szPath))
    {
        CBackgroundPainter::Instance().SetTextureBG(szPath.data);
    }

    // BUGFIX: If the shininess is 0.0f disable phong lighting
    // This is a workaround for some meshes in the DX SDK (e.g. tiny.x)
    // FIX: Added this check to the x-loader, but the line remains to
    // catch other loader doing the same ...
    if (0.0f == pcMesh->fShininess){
        pcMesh->eShadingMode = aiShadingMode_Gouraud;
    }

    int two_sided = 0;
    aiGetMaterialInteger(pcMat,AI_MATKEY_TWOSIDED,&two_sided);
    pcMesh->twosided = (two_sided != 0);

    // check whether we have already a material using the same
    // shader. This will decrease loading time rapidly ...
    for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes;++i)
    {
        if (g_pcAsset->pcScene->mMeshes[i] == pcSource)
        {
            break;
        }
        AssetHelper::MeshHelper* pc = g_pcAsset->apcMeshes[i];

        if  ((pcMesh->piDiffuseTexture != NULL ? true : false) !=
            (pc->piDiffuseTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piSpecularTexture != NULL ? true : false) !=
            (pc->piSpecularTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piAmbientTexture != NULL ? true : false) !=
            (pc->piAmbientTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piEmissiveTexture != NULL ? true : false) !=
            (pc->piEmissiveTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piNormalTexture != NULL ? true : false) !=
            (pc->piNormalTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piOpacityTexture != NULL ? true : false) !=
            (pc->piOpacityTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piShininessTexture != NULL ? true : false) !=
            (pc->piShininessTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piLightmapTexture != NULL ? true : false) !=
            (pc->piLightmapTexture != NULL ? true : false))
            continue;
        if ((pcMesh->eShadingMode != aiShadingMode_Gouraud ? true : false) !=
            (pc->eShadingMode != aiShadingMode_Gouraud ? true : false))
            continue;

        if ((pcMesh->fOpacity != 1.0f ? true : false) != (pc->fOpacity != 1.0f ? true : false))
            continue;

        if (pcSource->HasBones() != g_pcAsset->pcScene->mMeshes[i]->HasBones())
            continue;

        // we can reuse this material
        if (pc->piEffect)
        {
            pcMesh->piEffect = pc->piEffect;
            pc->bSharedFX = pcMesh->bSharedFX = true;
            pcMesh->piEffect->AddRef();
            return 2;
        }
    }
    m_iShaderCount++;

    // build macros for the HLSL compiler
    unsigned int iCurrent = 0;
    if (pcMesh->piDiffuseTexture)
    {
        sMacro[iCurrent].Name = "AV_DIFFUSE_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;

        if (mapU == aiTextureMapMode_Wrap)
            sMacro[iCurrent].Name = "AV_WRAPU";
        else if (mapU == aiTextureMapMode_Mirror)
            sMacro[iCurrent].Name = "AV_MIRRORU";
        else // if (mapU == aiTextureMapMode_Clamp)
            sMacro[iCurrent].Name = "AV_CLAMPU";

        sMacro[iCurrent].Definition = "1";
        ++iCurrent;


        if (mapV == aiTextureMapMode_Wrap)
            sMacro[iCurrent].Name = "AV_WRAPV";
        else if (mapV == aiTextureMapMode_Mirror)
            sMacro[iCurrent].Name = "AV_MIRRORV";
        else // if (mapV == aiTextureMapMode_Clamp)
            sMacro[iCurrent].Name = "AV_CLAMPV";

        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    if (pcMesh->piSpecularTexture)
    {
        sMacro[iCurrent].Name = "AV_SPECULAR_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    if (pcMesh->piAmbientTexture)
    {
        sMacro[iCurrent].Name = "AV_AMBIENT_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    if (pcMesh->piEmissiveTexture)
    {
        sMacro[iCurrent].Name = "AV_EMISSIVE_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    char buff[32];
    if (pcMesh->piLightmapTexture)
    {
        sMacro[iCurrent].Name = "AV_LIGHTMAP_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;

        int idx;
        if(AI_SUCCESS == aiGetMaterialInteger(pcMat,AI_MATKEY_UVWSRC_LIGHTMAP(0),&idx) && idx >= 1 && pcSource->mTextureCoords[idx])    {
            sMacro[iCurrent].Name = "AV_TWO_UV";
            sMacro[iCurrent].Definition = "1";
            ++iCurrent;

            sMacro[iCurrent].Definition = "IN.TexCoord1";
        }
        else sMacro[iCurrent].Definition = "IN.TexCoord0";
        sMacro[iCurrent].Name = "AV_LIGHTMAP_TEXTURE_UV_COORD";

        ++iCurrent;float f= 1.f;
        aiGetMaterialFloat(pcMat,AI_MATKEY_TEXBLEND_LIGHTMAP(0),&f);
        sprintf(buff,"%f",f);

        sMacro[iCurrent].Name = "LM_STRENGTH";
        sMacro[iCurrent].Definition = buff;
        ++iCurrent;
    }
    if (pcMesh->piNormalTexture && !bib)
    {
        sMacro[iCurrent].Name = "AV_NORMAL_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    if (pcMesh->piOpacityTexture)
    {
        sMacro[iCurrent].Name = "AV_OPACITY_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;

        if (pcMesh->piOpacityTexture == pcMesh->piDiffuseTexture)
        {
            sMacro[iCurrent].Name = "AV_OPACITY_TEXTURE_REGISTER_MASK";
            sMacro[iCurrent].Definition = "a";
            ++iCurrent;
        }
        else
        {
            sMacro[iCurrent].Name = "AV_OPACITY_TEXTURE_REGISTER_MASK";
            sMacro[iCurrent].Definition = "r";
            ++iCurrent;
        }
    }

    if (pcMesh->eShadingMode  != aiShadingMode_Gouraud  && !g_sOptions.bNoSpecular)
    {
        sMacro[iCurrent].Name = "AV_SPECULAR_COMPONENT";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;

        if (pcMesh->piShininessTexture)
        {
            sMacro[iCurrent].Name = "AV_SHININESS_TEXTURE";
            sMacro[iCurrent].Definition = "1";
            ++iCurrent;
        }
    }
    if (1.0f != pcMesh->fOpacity)
    {
        sMacro[iCurrent].Name = "AV_OPACITY";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }

    if( pcSource->HasBones())
    {
        sMacro[iCurrent].Name = "AV_SKINNING";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }

    // If a cubemap is active, we'll need to lookup it for calculating
    // a physically correct reflection
    if (CBackgroundPainter::TEXTURE_CUBE == CBackgroundPainter::Instance().GetMode())
    {
        sMacro[iCurrent].Name = "AV_SKYBOX_LOOKUP";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    sMacro[iCurrent].Name = NULL;
    sMacro[iCurrent].Definition = NULL;

    // compile the shader
    if(FAILED( D3DXCreateEffect(g_piDevice,
        g_szMaterialShader.c_str(),(UINT)g_szMaterialShader.length(),
        (const D3DXMACRO*)sMacro,NULL,0,NULL,&pcMesh->piEffect,&piBuffer)))
    {
        // failed to compile the shader
        if( piBuffer)
        {
            MessageBox(g_hDlg,(LPCSTR)piBuffer->GetBufferPointer(),"HLSL",MB_OK);
            piBuffer->Release();
        }
        // use the default material instead
        if (g_piDefaultEffect)
        {
            pcMesh->piEffect = g_piDefaultEffect;
            g_piDefaultEffect->AddRef();
        }

        // get the name of the material and use it in the log message
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_NAME,&szPath) &&
            '\0' != szPath.data[0])
        {
            std::string sz = "[ERROR] Unable to load material: ";
            sz.append(szPath.data);
            CLogDisplay::Instance().AddEntry(sz);
        }
        else
        {
            CLogDisplay::Instance().AddEntry("Unable to load material: UNNAMED");
        }
        return 0;
    } else
    {
        // use Fixed Function effect when working with shaderless cards
        if( g_sCaps.PixelShaderVersion < D3DPS_VERSION(2,0))
            pcMesh->piEffect->SetTechnique( "MaterialFX_FF");
    }

    if( piBuffer) piBuffer->Release();


    // now commit all constants to the shader
    //
    // This is not necessary for shared shader. Shader constants for
    // shared shaders are automatically recommited before the shader
    // is being used for a particular mesh

    if (1.0f != pcMesh->fOpacity)
        pcMesh->piEffect->SetFloat("TRANSPARENCY",pcMesh->fOpacity);
    if (pcMesh->eShadingMode  != aiShadingMode_Gouraud && !g_sOptions.bNoSpecular)
    {
        pcMesh->piEffect->SetFloat("SPECULARITY",pcMesh->fShininess);
        pcMesh->piEffect->SetFloat("SPECULAR_STRENGTH",pcMesh->fSpecularStrength);
    }

    pcMesh->piEffect->SetVector("DIFFUSE_COLOR",&pcMesh->vDiffuseColor);
    pcMesh->piEffect->SetVector("SPECULAR_COLOR",&pcMesh->vSpecularColor);
    pcMesh->piEffect->SetVector("AMBIENT_COLOR",&pcMesh->vAmbientColor);
    pcMesh->piEffect->SetVector("EMISSIVE_COLOR",&pcMesh->vEmissiveColor);

    if (pcMesh->piDiffuseTexture)
        pcMesh->piEffect->SetTexture("DIFFUSE_TEXTURE",pcMesh->piDiffuseTexture);
    if (pcMesh->piOpacityTexture)
        pcMesh->piEffect->SetTexture("OPACITY_TEXTURE",pcMesh->piOpacityTexture);
    if (pcMesh->piSpecularTexture)
        pcMesh->piEffect->SetTexture("SPECULAR_TEXTURE",pcMesh->piSpecularTexture);
    if (pcMesh->piAmbientTexture)
        pcMesh->piEffect->SetTexture("AMBIENT_TEXTURE",pcMesh->piAmbientTexture);
    if (pcMesh->piEmissiveTexture)
        pcMesh->piEffect->SetTexture("EMISSIVE_TEXTURE",pcMesh->piEmissiveTexture);
    if (pcMesh->piNormalTexture)
        pcMesh->piEffect->SetTexture("NORMAL_TEXTURE",pcMesh->piNormalTexture);
    if (pcMesh->piShininessTexture)
        pcMesh->piEffect->SetTexture("SHININESS_TEXTURE",pcMesh->piShininessTexture);
    if (pcMesh->piLightmapTexture)
        pcMesh->piEffect->SetTexture("LIGHTMAP_TEXTURE",pcMesh->piLightmapTexture);

    if (CBackgroundPainter::TEXTURE_CUBE == CBackgroundPainter::Instance().GetMode()){
        pcMesh->piEffect->SetTexture("lw_tex_envmap",CBackgroundPainter::Instance().GetTexture());
    }

    return 1;
}
Esempio n. 17
0
bool CDirect3D::SetShaderHLSL(const TCHAR *file)
{
	//MUDLORD: the guts
	//Compiles a shader from files on disc
	//Sets LUT textures to texture files in PNG format.

	TCHAR folder[MAX_PATH];
	TCHAR rubyLUTfileName[MAX_PATH];
	TCHAR *slash;

	TCHAR errorMsg[MAX_PATH + 50];

	shaderTimer = 1.0f;
	shaderTimeStart = 0;
	shaderTimeElapsed = 0;

	if(effect) {
		effect->Release();
		effect = NULL;
	}
	for(int i = 0; i < MAX_SHADER_TEXTURES; i++) {
		if (rubyLUT[i] != NULL) {
			rubyLUT[i]->Release();
			rubyLUT[i] = NULL;
		}
	}
	if (file == NULL || *file==TEXT('\0'))
		return true;

	CXML xml;

    if(!xml.loadXmlFile(file))
        return false;

    TCHAR *lang = xml.getAttribute(TEXT("/shader"),TEXT("language"));

	if(lstrcmpi(lang,TEXT("hlsl"))) {
		_stprintf(errorMsg,TEXT("Shader language is <%s>, expected <HLSL> in file:\n%s"),lang,file);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK|MB_ICONEXCLAMATION);
		return false;
	}

    TCHAR *shaderText = xml.getNodeContent(TEXT("/shader/source"));

	if(!shaderText) {
		_stprintf(errorMsg,TEXT("No HLSL shader program in file:\n%s"),file);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"),
			MB_OK|MB_ICONEXCLAMATION);
		return false;
	}

	LPD3DXBUFFER pBufferErrors = NULL;
#ifdef UNICODE
    HRESULT hr = D3DXCreateEffect( pDevice,WideToCP(shaderText,CP_ACP),strlen(WideToCP(shaderText,CP_ACP)),NULL, NULL,
		D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY, NULL, &effect, 
		&pBufferErrors );
#else
	HRESULT hr = D3DXCreateEffect( pDevice,shaderText,strlen(shaderText),NULL, NULL,
		D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY, NULL, &effect, 
		&pBufferErrors );
#endif

    if( FAILED(hr) ) {
		_stprintf(errorMsg,TEXT("Error parsing HLSL shader file:\n%s"),file);
		MessageBox(NULL, errorMsg, TEXT("Shader Loading Error"), MB_OK|MB_ICONEXCLAMATION);
		if(pBufferErrors) {
			LPVOID pCompilErrors = pBufferErrors->GetBufferPointer();
			MessageBox(NULL, (const TCHAR*)pCompilErrors, TEXT("FX Compile Error"),
				MB_OK|MB_ICONEXCLAMATION);
		}
		return false;
	}

	lstrcpy(folder,file);
	slash = _tcsrchr(folder,TEXT('\\'));
	if(slash)
		*(slash+1)=TEXT('\0');
	else
		*folder=TEXT('\0');
	SetCurrentDirectory(S9xGetDirectoryT(DEFAULT_DIR));

	for(int i = 0; i < MAX_SHADER_TEXTURES; i++) {		
		_stprintf(rubyLUTfileName, TEXT("%srubyLUT%d.png"), folder, i);
		hr = D3DXCreateTextureFromFile(pDevice,rubyLUTfileName,&rubyLUT[i]);
		if FAILED(hr){
			rubyLUT[i] = NULL;
		}
	}

	D3DXHANDLE hTech;
	effect->FindNextValidTechnique(NULL,&hTech);
	effect->SetTechnique( hTech );
	shader_type = D3D_SHADER_HLSL;
	return true;
}
bool U2D3DXEffectShader::LoadResource()
{
	U2ASSERT(0 == m_pD3DEffect);

	HRESULT hr;
	
	IDirect3DDevice9* pD3DDev = m_pRenderer->GetD3DDevice();
	U2ASSERT(pD3DDev);

	U2FilePath fPath;		
	TCHAR fullPath[MAX_PATH];
	// StackString Memory Leak...
	U2DynString includePath(FX_SHADER_PATH);
	includePath += _T("\\2.0");

	fPath.ConvertToAbs(fullPath, MAX_PATH * sizeof(TCHAR) , m_szFilename.Str(), includePath);		

	U2File* pFile = U2File::GetFile(fullPath, U2File::READ_ONLY);
	if(!pFile)
	{
		U2_DELETE pFile;
		return false;
	}

	uint32 uBuffLen = pFile->GetfileSize();
	if(uBuffLen == 0)
	{
		U2_DELETE pFile;
		return false;
	}

	unsigned char* pBuffer = U2_ALLOC(unsigned char, uBuffLen);
	pFile->Read(pBuffer, uBuffLen);

	U2_DELETE pFile;

	ID3DXBuffer* pErrorBuffer = NULL;

#ifdef DEBUG_SHADER
	DWORD compileFlags = D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION | D3DXSHADER_USE_LEGACY_D3DX9_31_DLL
		| D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT | D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT ;	
#else
	DWORD compileFlags = D3DXSHADER_USE_LEGACY_D3DX9_31_DLL;
#endif

	//U2DynString includePath(FX_SHADER_PATH);
	//includePath += _T("\\2.0");
	
	U2D3DXEffectShaderInclude includeHandler(includePath);

	ID3DXEffectPool* pEffectPool = m_pRenderer->GetD3DEffectPool();
	U2ASSERT(pEffectPool);

	// get the highest supported shader profiles
//	LPCSTR vsProfile, psProfile;
//#ifdef UNICODE 
//	 vsProfile = ToUnicode( D3DXGetVertexShaderProfile(pD3DDev) );
//	 psProfile = ToUnicode( D3DXGetPixelShaderProfile(pD3DDev) );
//#else 
//	vsProfile = D3DXGetVertexShaderProfile(pD3DDev);
//	psProfile = D3DXGetPixelShaderProfile(pD3DDev);
//#endif
	LPCSTR vsProfile = D3DXGetVertexShaderProfile(pD3DDev);
	LPCSTR psProfile = D3DXGetPixelShaderProfile(pD3DDev);

	if (0 == vsProfile)
	{
		FDebug("Invalid Vertex Shader profile! Fallback to vs_2_0!\n");
		vsProfile = "vs_2_0";
	}

	if (0 == psProfile)
	{
		FDebug("Invalid Pixel Shader profile! Fallback to ps_2_0!\n");
		psProfile = "ps_2_0";
	}

	// create macro definitions for shader compiler
	D3DXMACRO defines[] = {
		{ "VS_PROFILE", vsProfile },
		{ "PS_PROFILE", psProfile },
		{ 0, 0 },
	};

	// create effect
	if (compileFlags)
	{
		hr = D3DXCreateEffectFromFile(
			pD3DDev,            // pDevice
			fullPath,   // File name
			defines,            // pDefines
			&includeHandler,    // pInclude
			compileFlags,       // Flags
			pEffectPool,         // pPool
			&m_pD3DEffect,    // ppEffect
			&pErrorBuffer);      // ppCompilationErrors
	}
	else
	{
		hr = D3DXCreateEffect(
			pD3DDev,            // pDevice
			pBuffer,             // pFileData
			uBuffLen,           // DataSize
			defines,            // pDefines
			&includeHandler,    // pInclude
			compileFlags,       // Flags
			pEffectPool,         // pPool
			&(m_pD3DEffect),    // ppEffect
			&pErrorBuffer);      // ppCompilationErrors
	}

	U2_FREE(pBuffer);
	pBuffer = NULL;

	if (FAILED(hr))
	{
		FDebug("nD3D9Shader: failed to load fx file '%s' with:\n\n%s\n",
			fullPath,
			pErrorBuffer ? pErrorBuffer->GetBufferPointer() : "No D3DX error message.");
		if (pErrorBuffer)
		{
			pErrorBuffer->Release();
		}
		return false;
	}
	U2ASSERT(m_pD3DEffect);

	m_bValidated = false;
	m_bNotValidate = false;

	this->ValidateEffect();

	return true;
}
Esempio n. 19
0
//--------------------------------------------------------------------------------------
//LoadShaderFromResource
//
//loads shader given a resource id
//--------------------------------------------------------------------------------------
HRESULT CEffect::LoadShaderFromResource(uint32 a_ResourceID, IDirect3DDevice9 *a_pDevice)
{
   HRESULT hr;
   ID3DXBuffer *errorBuffer;
   HRSRC       resourceInfo;
   HGLOBAL     resourceData;
   char8       *shaderText;

   m_pDevice = a_pDevice;

   //delete old effect if multiple calls to load shader are made
   SAFE_RELEASE(m_pEffect);

   // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the 
   // shader debugger. Debugging vertex shaders requires either REF or software vertex 
   // processing, and debugging pixel shaders requires REF.  The 
   // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the 
   // shader debugger.  It enables source level debugging, prevents instruction 
   // reordering, prevents dead code elimination, and forces the compiler to compile 
   // against the next higher available software target, which ensures that the 
   // unoptimized shaders do not exceed the shader model limitations.  Setting these 
   // flags will cause slower rendering since the shaders will be unoptimized and 
   // forced into software.  See the DirectX documentation for more information about 
   // using the shader debugger.
   DWORD dwShaderFlags = 0;
   #ifdef DEBUG_VS
      dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
   #endif
   #ifdef DEBUG_PS
      dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
   #endif

   //load shadertext from resource
   resourceInfo = FindResource(NULL, MAKEINTRESOURCE(a_ResourceID), L"EFFECTFILE"); 

   if(resourceInfo == NULL)
   {
      _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Resource %d of type ''EFFECTFILE'' not found.", a_ResourceID );   
   }

   resourceData = LoadResource(NULL, resourceInfo ); 

   shaderText = (char8 *)LockResource( resourceData);

   //Create effect from text loaded from resource
   // load and compile .fx file
   // If this fails, there should be debug output as to 
   // why the .fx file failed to compile
   hr = D3DXCreateEffect(
      m_pDevice,           //LPDIRECT3DDEVICE9 pDevice,
      shaderText,          //LPCVOID pSrcData,
      (uint32)SizeofResource(NULL, resourceInfo),  //UINT SrcDataLen,
      NULL,                //const D3DXMACRO *pDefines,
      NULL,                //LPD3DXINCLUDE pInclude,
      0,                   //DWORD Flags,
      NULL,                //LPD3DXEFFECTPOOL pPool,
      &m_pEffect,          //LPD3DXEFFECT *ppEffect,
      &errorBuffer         //LPD3DXBUFFER *ppCompilationErrors
      );
      
   UnlockResource( resourceData );
   FreeResource( resourceData );

   //return failure and record error message if failure
   if(FAILED(hr))
   {  //error is in 8-bit character format, so for swprintf to use the string, %S (capital S) is used.
      if(errorBuffer != NULL)
      {
         _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Shader Compile Error: %S.", errorBuffer->GetBufferPointer() );
      }
      else
      {
         _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Shader Compile Error: no output from D3DXCreateEffectFromResource." );      
      }

      SAFE_RELEASE(errorBuffer);
      return hr;
   }

   _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"FX file in Resource %d Compiled Successfully.", a_ResourceID);

   return S_OK;
}
Esempio n. 20
0
void CDXShader::CreateEffect(LPDIRECT3DDEVICE9 pDevice)
{
	/*const char* g_strBuffer = "float3 g_vMaterialAmbient : Ambient = float3( 0.2f, 0.2f, 0.2f );   // Material's ambient color\r\n"
		"float3 g_vMaterialDiffuse : Diffuse = float3( 1.0f, 1.0f, 1.0f );   // Material's diffuse color\r\n"
		"float3 g_vMaterialSpecular : Specular = float3( 1.0f, 1.0f, 1.0f );  // Material's specular color\r\n"
		"float  g_fMaterialAlpha : Opacity = 1.0f;\r\n"
		"int    g_nMaterialShininess : SpecularPower = 32;\r\n"
		"float3 g_vLightColor : LightColor = float3( 1.0f, 1.0f, 1.0f );        // Light color\r\n"
		"float3 g_vLightPosition : LightPosition = float3( 50.0f, 10.0f, 0.0f );   // Light position\r\n"
		"float3 g_vCameraPosition : CameraPosition;\r\n"
		"texture  g_MeshTexture : Texture;   // Color texture for mesh\r\n"
		"float    g_fTime : Time;            // App's time in seconds\r\n"
		"float4x4 g_mWorld : World;          // World matrix\r\n"
		"float4x4 g_mWorldViewProjection : WorldViewProjection; // World * View * Projection matrix\r\n"
		"sampler MeshTextureSampler = \r\n"
		"	sampler_state\r\n"
		"{\r\n"
		"	Texture = <g_MeshTexture>;\r\n"
		"	MipFilter = LINEAR;\r\n"
		"	MinFilter = LINEAR;\r\n"
		"	MagFilter = LINEAR;\r\n"
		"};\r\n"
		"void Projection( float4 vPosObject: POSITION,\r\n"
		"	float3 vNormalObject: NORMAL,\r\n"
		"	float2 vTexCoordIn: TEXCOORD0,\r\n"
		"	out float4 vPosProj: POSITION,\r\n"
		"	out float2 vTexCoordOut: TEXCOORD0,\r\n"
		"	out float4 vColorOut: COLOR0,\r\n"
		"	uniform bool bSpecular\r\n"
		"	)\r\n"
		"{\r\n"
		"	float4 vPosWorld = mul( vPosObject, g_mWorld );\r\n"
		"	vPosProj = mul( vPosObject, g_mWorldViewProjection );\r\n"
		"	float3 vNormalWorld = mul( vNormalObject, (float3x3)g_mWorld );\r\n"
		"	vTexCoordOut = vTexCoordIn;\r\n"
		"	float3 vLight = normalize( g_vLightPosition - vPosWorld.xyz );\r\n"
		"	vColorOut.rgb = g_vLightColor * g_vMaterialAmbient;\r\n"
		"	vColorOut.rgb += g_vLightColor * g_vMaterialDiffuse * saturate( dot( vLight, vNormalWorld ) );\r\n"
		"	if( bSpecular )\r\n"
		"	{\r\n"
		"		float3 vCamera = normalize(vPosWorld.xyz - g_vCameraPosition);\r\n"
		"		float3 vReflection = reflect( vLight, vNormalWorld );\r\n"
		"		float  fPhongValue = saturate( dot( vReflection, vCamera ) );\r\n"
		"		vColorOut.rgb += g_vMaterialSpecular * pow(fPhongValue, g_nMaterialShininess);\r\n"
		"	}\r\n"
		"	vColorOut.a = g_fMaterialAlpha;\r\n"
		"}\r\n"
		"void Lighting( float2 vTexCoord: TEXCOORD0,\r\n"
		"	float4 vColorIn: COLOR0,\r\n"
		"	out float4 vColorOut: COLOR0,\r\n"
		"	uniform bool bTexture )\r\n"
		"{\r\n"
		"	vColorOut = vColorIn;\r\n"
		"	if( bTexture )\r\n"
		"		vColorOut.rgb *= tex2D( MeshTextureSampler, vTexCoord );\r\n"
		"}\r\n"
		"technique Specular\r\n"
		"{\r\n"
		"	pass P0\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Projection(true);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(false);\r\n"
		"	}\r\n"
		"}\r\n"
		"technique NoSpecular\r\n"
		"{\r\n"
		"	pass P0\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Projection(false);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(false);\r\n"
		"	}\r\n"
		"}\r\n"
		"technique TexturedSpecular\r\n"
		"{\r\n"
		"	pass P0\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Projection(true);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(true);\r\n"
		"	}\r\n"
		"}\r\n"
		"technique TexturedNoSpecular\r\n"
		"{\r\n"
		"	pass P0\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Projection(false);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(true);\r\n"
		"	}\r\n"
		"}\r\n";*/
	const char* g_strBuffer = "float3 g_vMaterialAmbient : Ambient = float3( 0.2f, 0.2f, 0.2f );   // Material's ambient color\r\n"
		"float3 g_vMaterialDiffuse : Diffuse = float3( 1.0f, 1.0f, 1.0f );   // Material's diffuse color\r\n"
		"float3 g_vMaterialSpecular : Specular = float3( 1.0f, 1.0f, 1.0f );  // Material's specular color\r\n"
		"float  g_fMaterialAlpha : Opacity = 1.0f;\r\n"
		"float  g_fMaterialAlphaThreshold : AlphaThreshold = 0.0f;\r\n"
		"int    g_nMaterialShininess : SpecularPower = 32;\r\n"
		"float3 g_vLightColor : LightColor = float3( 1.0f, 1.0f, 1.0f );        // Light color\r\n"
		"float3 g_vLightPosition : LightPosition = float3( 0.0f, -100.0f, 0.0f );   // Light position\r\n"
		"float3 g_vCameraPosition : CameraPosition;\r\n"
		"float3 g_vWireframe : WireframeColor = float3( 1.0f, 1.0f, 1.0f);\r\n"
		"texture  g_MeshTexture : Texture;   // Color texture for mesh\r\n"
		"float    g_fTime : Time;            // App's time in seconds\r\n"
		"float4x4 g_mWorld : World;          // World matrix\r\n"
		"float4x4 g_mWorldViewProjection : WorldViewProjection; // World * View * Projection matrix\r\n"
		"float4x4	g_mTransform: Transform;\r\n"
		"sampler DiffuseSampler = \r\n"
		"	sampler_state\r\n"
		"{\r\n"
		"	Texture = <g_MeshTexture>;\r\n"
		"	MipFilter = LINEAR;\r\n"
		"	MinFilter = LINEAR;\r\n"
		"	MagFilter = LINEAR;\r\n"
		"	AddressU = WRAP;\r\n"
		"	AddressV = WRAP;\r\n"
		"	AddressW = WRAP;\r\n"
		"};\r\n"
		"void Basic( float4 vPosObject: POSITION0,\r\n"
		"	float3 vNormalObject: NORMAL0,\r\n"
		"	float2 vTexCoordIn: TEXCOORD0,\r\n"
		"	float4 vColorIn: COLOR0,\r\n"
		"	float4 vColorSelect: COLOR1,\r\n"
		"	out float4 vPosProj: POSITION,\r\n"
		"	out float2 vTexCoordOut: TEXCOORD0,\r\n"
		"	out float4 vColorOut: COLOR0,\r\n"
		"	uniform float fLine )\r\n"
		"{\r\n"
		"	float4 vPosTransform = mul(vPosObject, g_mTransform);\r\n"
		"	vPosTransform.xyz *= fLine;\r\n"
		"	vPosProj = mul( vPosTransform, g_mWorldViewProjection );\r\n"
		"	vTexCoordOut = vTexCoordIn;\r\n"
		"	vColorOut.a = g_fMaterialAlpha;\r\n"
		"	vColorOut.rgb = g_vWireframe;\r\n"
		"}\r\n"
		"void Projection( float4 vPosObject: POSITION0,\r\n"
		"	float3 vNormalObject: NORMAL0,\r\n"
		"	float2 vTexCoordIn: TEXCOORD0,\r\n"
		"	float4 vColorIn: COLOR0,\r\n"
		"	out float4 vPosProj: POSITION,\r\n"
		"	out float2 vTexCoordOut: TEXCOORD0,\r\n"
		"	out float4 vColorOut: COLOR0,\r\n"
		"	uniform bool bSpecular )\r\n"
		"{\r\n"
		"	float4 vPosTransform = mul(vPosObject, g_mTransform);\r\n"
		"	float4 vPosWorld = mul( vPosTransform, g_mWorld );\r\n"
		"	vPosProj = mul( vPosTransform, g_mWorldViewProjection );\r\n"
		"	float3 vNormalWorld = mul( vNormalObject, (float3x3)g_mWorld );\r\n"
		"	vTexCoordOut = vTexCoordIn;\r\n"
		"	float3 vLight = normalize( g_vLightPosition - vPosWorld.xyz );\r\n"
		"	vColorOut.rgb = g_vLightColor * g_vMaterialAmbient;\r\n"
		"	vColorOut.rgb += g_vLightColor * g_vMaterialDiffuse * saturate( dot( vLight, vNormalWorld ) );\r\n"
		"	if( bSpecular ) {\r\n"
		"		float3 vCamera = normalize(vPosWorld.xyz - g_vCameraPosition);\r\n"
		"		float3 vReflection = reflect( vLight, vNormalWorld );\r\n"
		"		float  fPhongValue = saturate( dot( vReflection, vCamera ) );\r\n"
		"		vColorOut.rgb += g_vMaterialSpecular * pow(fPhongValue, g_nMaterialShininess);\r\n"
		"	}\r\n"
		"	vColorOut.a = g_fMaterialAlpha;\r\n"
		"	vColorOut *= vColorIn;\r\n"
		"}\r\n"
		"void Lighting( float4 vPos: POSITION0,\r\n"
		"	float2 vTexCoord: TEXCOORD0,\r\n"
		"	float4 vColorIn: COLOR0,\r\n"
		"	out float4 vColorOut: COLOR0,\r\n"
		"	uniform bool bTexture )\r\n"
		"{\r\n"
		"	vColorOut = vColorIn;\r\n"
		"	if( bTexture )\r\n"
		"		vColorOut *= tex2D( DiffuseSampler, vTexCoord );\r\n"
		"}\r\n"
		"technique Specular\r\n"
		"{\r\n"
		"	pass P0\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Projection(true);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(false);\r\n"
		"	}\r\n"
		"}\r\n"
		"technique Wireframe\r\n"
		"{\r\n"
		"	pass P0\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Basic(1.000f);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(false);\r\n"
		"	}\r\n"
		"	pass P1\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Basic(1.002f);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(false);\r\n"
		"	}\r\n"
		"	pass P2\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Basic(1.004f);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(false);\r\n"
		"	}\r\n"
		"}\r\n"
		"technique NoSpecular\r\n"
		"{\r\n"
		"	pass P0\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Projection(false);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(false);\r\n"
		"	}\r\n"
		"}\r\n"
		"technique TexturedSpecular\r\n"
		"{\r\n"
		"	pass P0\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Projection(true);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(true);\r\n"
		"	}\r\n"
		"}\r\n"
		"technique TexturedNoSpecular\r\n"
		"{\r\n"
		"	pass P0\r\n"
		"	{\r\n"
		"		VertexShader = compile vs_2_0 Projection(false);\r\n"
		"		PixelShader = compile ps_2_0 Lighting(true);\r\n"
		"	}\r\n"
		"}\r\n";

	UINT dwBufferSize = ( UINT )strlen( g_strBuffer ) + 1;

	try
	{
		if (D3DXCreateEffect(pDevice, g_strBuffer, dwBufferSize, NULL, NULL, D3DXFX_NOT_CLONEABLE, NULL, &m_pEffect, NULL) == D3D_OK)
		{
			if (m_pEffect) {
				m_hAmbient = m_pEffect->GetParameterBySemantic(0, "Ambient");
				m_hDiffuse = m_pEffect->GetParameterBySemantic(0, "Diffuse");
				m_hSpecular = m_pEffect->GetParameterBySemantic(0, "Specular");
				m_hOpacity = m_pEffect->GetParameterBySemantic(0, "Opacity");
				m_hSpecularPower = m_pEffect->GetParameterBySemantic(0, "SpecularPower");
				m_hLightColor = m_pEffect->GetParameterBySemantic(0, "LightColor");
				m_hLightPosition = m_pEffect->GetParameterBySemantic(0, "LightPosition");
				m_hCameraPosition = m_pEffect->GetParameterBySemantic(0, "CameraPosition");
				m_hTexture = m_pEffect->GetParameterBySemantic(0, "Texture");
				m_hTime = m_pEffect->GetParameterBySemantic(0, "Time");
				m_hWorld = m_pEffect->GetParameterBySemantic(0, "World");
				m_hWorldViewProjection = m_pEffect->GetParameterBySemantic(0, "WorldViewProjection");
				m_hWireframeColor = m_pEffect->GetParameterBySemantic(0, "WireframeColor");
				m_hTransform = m_pEffect->GetParameterBySemantic(0, "Transform");
			}
		}
	}
	catch ( ... )
	{
		_ERROR("%s - Fatal error creating D3D Effect.", __FUNCTION__);
		m_pEffect = nullptr;
	}
}
Esempio n. 21
0
static void test_create_effect_and_pool(IDirect3DDevice9 *device)
{
    HRESULT hr;
    ID3DXEffect *effect;
    ID3DXBaseEffect *base;
    ULONG count;
    IDirect3DDevice9 *device2;
    LPD3DXEFFECTSTATEMANAGER manager = (LPD3DXEFFECTSTATEMANAGER)0xdeadbeef;
    ID3DXEffectPool *pool = (ID3DXEffectPool *)0xdeadbeef, *pool2;

    hr = D3DXCreateEffect(NULL, effect_desc, sizeof(effect_desc), NULL, NULL, 0, NULL, NULL, NULL);
    ok(hr == D3DERR_INVALIDCALL, "Got result %x, expected %x (D3D_INVALIDCALL)\n", hr, D3DERR_INVALIDCALL);

    hr = D3DXCreateEffect(device, NULL, 0, NULL, NULL, 0, NULL, NULL, NULL);
    ok(hr == D3DERR_INVALIDCALL, "Got result %x, expected %x (D3DERR_INVALIDCALL)\n", hr, D3DERR_INVALIDCALL);

    hr = D3DXCreateEffect(device, effect_desc, 0, NULL, NULL, 0, NULL, NULL, NULL);
    ok(hr == E_FAIL, "Got result %x, expected %x (D3DXERR_INVALIDDATA)\n", hr, E_FAIL);

    hr = D3DXCreateEffect(device, effect_desc, sizeof(effect_desc), NULL, NULL, 0, NULL, NULL, NULL);
    ok(hr == D3D_OK, "Got result %x, expected 0 (D3D_OK)\n", hr);

    hr = D3DXCreateEffect(device, effect_desc, sizeof(effect_desc), NULL, NULL, 0, NULL, &effect, NULL);
    ok(hr == D3D_OK, "Got result %x, expected 0 (D3D_OK)\n", hr);

    hr = effect->lpVtbl->QueryInterface(effect, &IID_ID3DXBaseEffect, (void **)&base);
    ok(hr == E_NOINTERFACE, "QueryInterface failed, got %x, expected %x (E_NOINTERFACE)\n", hr, E_NOINTERFACE);

    hr = effect->lpVtbl->GetStateManager(effect, NULL);
    ok(hr == D3DERR_INVALIDCALL, "GetStateManager failed, got %x, expected %x (D3DERR_INVALIDCALL)\n", hr, D3DERR_INVALIDCALL);

    hr = effect->lpVtbl->GetStateManager(effect, &manager);
    ok(hr == D3D_OK, "GetStateManager failed, got %x, expected 0 (D3D_OK)\n", hr);
    ok(!manager, "GetStateManager failed, got %p\n", manager);

    /* this works, but it is not recommended! */
    hr = effect->lpVtbl->SetStateManager(effect, (LPD3DXEFFECTSTATEMANAGER) device);
    ok(hr == D3D_OK, "SetStateManager failed, got %x, expected 0 (D3D_OK)\n", hr);

    hr = effect->lpVtbl->GetStateManager(effect, &manager);
    ok(hr == D3D_OK, "GetStateManager failed, got %x, expected 0 (D3D_OK)\n", hr);
    ok(manager != NULL, "GetStateManager failed\n");

    IDirect3DDevice9_AddRef(device);
    count = IDirect3DDevice9_Release(device);
    ok(count == 4, "Release failed, got %u, expected 4\n", count);

    count = IUnknown_Release(manager);
    ok(count == 3, "Release failed, got %u, expected 3\n", count);

    hr = effect->lpVtbl->SetStateManager(effect, NULL);
    ok(hr == D3D_OK, "SetStateManager failed, got %x, expected 0 (D3D_OK)\n", hr);

    hr = effect->lpVtbl->GetPool(effect, &pool);
    ok(hr == D3D_OK, "GetPool failed, got %x, expected 0 (D3D_OK)\n", hr);
    ok(!pool, "GetPool failed, got %p\n", pool);

    hr = effect->lpVtbl->GetPool(effect, NULL);
    ok(hr == D3DERR_INVALIDCALL, "GetPool failed, got %x, expected %x (D3DERR_INVALIDCALL)\n", hr, D3DERR_INVALIDCALL);

    hr = effect->lpVtbl->GetDevice(effect, &device2);
    ok(hr == D3D_OK, "Got result %x, expected 0 (D3D_OK)\n", hr);

    hr = effect->lpVtbl->GetDevice(effect, NULL);
    ok(hr == D3DERR_INVALIDCALL, "GetDevice failed, got %x, expected %x (D3DERR_INVALIDCALL)\n", hr, D3DERR_INVALIDCALL);

    count = IDirect3DDevice9_Release(device2);
    ok(count == 2, "Release failed, got %u, expected 2\n", count);

    count = effect->lpVtbl->Release(effect);
    ok(count == 0, "Release failed %u\n", count);

    hr = D3DXCreateEffectPool(NULL);
    ok(hr == D3DERR_INVALIDCALL, "Got result %x, expected %x (D3D_INVALIDCALL)\n", hr, D3DERR_INVALIDCALL);

    hr = D3DXCreateEffectPool(&pool);
    ok(hr == S_OK, "Got result %x, expected 0 (S_OK)\n", hr);

    count = pool->lpVtbl->Release(pool);
    ok(count == 0, "Release failed %u\n", count);

    hr = D3DXCreateEffectPool(&pool);
    ok(hr == S_OK, "Got result %x, expected 0 (S_OK)\n", hr);

    hr = D3DXCreateEffect(device, effect_desc, sizeof(effect_desc), NULL, NULL, 0, pool, NULL, NULL);
    ok(hr == D3D_OK, "Got result %x, expected 0 (D3D_OK)\n", hr);

    hr = pool->lpVtbl->QueryInterface(pool, &IID_ID3DXEffectPool, (void **)&pool2);
    ok(hr == D3D_OK, "Got result %x, expected 0 (D3D_OK)\n", hr);
    ok(pool == pool2, "Release failed, got %p, expected %p\n", pool2, pool);

    count = pool2->lpVtbl->Release(pool2);
    ok(count == 1, "Release failed, got %u, expected 1\n", count);

    hr = IDirect3DDevice9_QueryInterface(device, &IID_IDirect3DDevice9, (void **)&device2);
    ok(hr == D3D_OK, "Got result %x, expected 0 (D3D_OK)\n", hr);

    count = IDirect3DDevice9_Release(device2);
    ok(count == 1, "Release failed, got %u, expected 1\n", count);

    hr = D3DXCreateEffect(device, effect_desc, sizeof(effect_desc), NULL, NULL, 0, pool, &effect, NULL);
    ok(hr == D3D_OK, "Got result %x, expected 0 (D3D_OK)\n", hr);

    hr = effect->lpVtbl->GetPool(effect, &pool);
    ok(hr == D3D_OK, "GetPool failed, got %x, expected 0 (D3D_OK)\n", hr);
    ok(pool == pool2, "GetPool failed, got %p, expected %p\n", pool2, pool);

    count = pool2->lpVtbl->Release(pool2);
    ok(count == 2, "Release failed, got %u, expected 2\n", count);

    count = effect->lpVtbl->Release(effect);
    ok(count == 0, "Release failed %u\n", count);

    count = pool->lpVtbl->Release(pool);
    ok(count == 0, "Release failed %u\n", count);
}
Esempio n. 22
0
void MyGame3DDevice::InitSceneEffectShader()
{
    // load shader
    HRSRC hResource = ::FindResource( NULL, MAKEINTRESOURCE(IDR_PIXEL_SHADER2), RT_RCDATA );
    HGLOBAL hResourceData = ::LoadResource( NULL, hResource );
    LPVOID pData = ::LockResource( hResourceData );

    ID3DXBuffer* errorBuffer = 0;
    HR( D3DXCreateEffect( pD3D9InstanceDevice,
                          pData,
                          ::SizeofResource( NULL, hResource ),
                          0,
                          0,
                          0,
                          0,
                          &mFX,
                          &errorBuffer ) );
    if( errorBuffer )
    {
        MyGameMessage( (char*)errorBuffer->GetBufferPointer() );
        errorBuffer->Release();
        return;
    }

    //initialize matrix in shader

    D3DXMATRIX worldMatrix;

    D3DXMatrixTranslation( &worldMatrix, -512.0f, -384.0f, 0 );

    D3DXVECTOR3 position( 0.0f, 0.0f, 20.0f );
    D3DXVECTOR3 targetPoint( 0.0f, 0.0f ,0.0f );
    D3DXVECTOR3 upVector( 0.0f, -1.0f, 0.0f );

    D3DXMATRIX	viewMatrix;

    D3DXMatrixLookAtLH( &viewMatrix, &position, &targetPoint, &upVector );

    D3DXMATRIX  projMatrix;

    D3DXMatrixOrthoLH( &projMatrix, 1024.0f, 768.0f, -1009.0f, 5000.0f );

    D3DXMatrixTranslation( &uiMoveMatrix, 0.0f, 0.0f, 0 );

    mhUIWorldMatHandle	= mFX->GetParameterByName( 0, worldMatName );
    mhUIViewMatHandle	= mFX->GetParameterByName( 0, viewMatName );
    mhUIProjMatHandle	= mFX->GetParameterByName( 0, projMatName );
    mhUIMoveMatHandle	= mFX->GetParameterByName( 0, moveMatName );
    mhAlphaEnabled		= mFX->GetParameterByName( 0, "alphaEnable" );
    D3DXHANDLE mhTech	= mFX->GetTechniqueByName( techniqueName );

    mhTex = mFX->GetParameterByName( 0, "gTex" );

    mFX->SetMatrix( mhUIWorldMatHandle, &worldMatrix );
    mFX->SetMatrix( mhUIViewMatHandle, &viewMatrix );
    mFX->SetMatrix( mhUIProjMatHandle, &projMatrix );
    mFX->SetMatrix( mhUIMoveMatHandle, &uiMoveMatrix );

    mFX->SetTechnique( mhTech );

    HR(mFX->SetBool( mhAlphaEnabled, FALSE ));

    return;
}
Esempio n. 23
0
HRESULT ScalingEffect::LoadEffect(const TCHAR *filename)
{
    KillThis();

    LPD3DXBUFFER		lpBufferEffect = 0;
    LPD3DXBUFFER		lpErrors = 0;
    LPD3DXEFFECTCOMPILER	lpEffectCompiler = 0;

    m_strErrors += filename;
    m_strErrors += ":\n";

    // First create an effect compiler
    HRESULT hr = D3DXCreateEffectCompilerFromFile(filename, NULL, NULL,NULL,
						&lpEffectCompiler, &lpErrors);
	
    // Errors...
    if(FAILED(hr)) {
	if(lpErrors) {
	    m_strErrors += (char*) lpErrors->GetBufferPointer();
	    SAFE_RELEASE(lpErrors);
	}

	m_strErrors += "Unable to create effect compiler from ";
	m_strErrors += filename;
    }

    if(SUCCEEDED(hr)) {
#ifdef C_D3DSHADERS_COMPILE_WITH_DEBUG
	hr = lpEffectCompiler->CompileEffect(D3DXSHADER_DEBUG, &lpBufferEffect, &lpErrors);
#else
	hr = lpEffectCompiler->CompileEffect(0, &lpBufferEffect, &lpErrors);
#endif
	
	// Errors...
	if(FAILED(hr)) {
	    if(lpErrors) {
		m_strErrors += (char*) lpErrors->GetBufferPointer();
		SAFE_RELEASE(lpErrors);
	    }

	    m_strErrors += "Unable to compile effect from ";
	    m_strErrors += filename;
	}
    }

    if(SUCCEEDED(hr)) {
	hr = D3DXCreateEffect(m_pd3dDevice,
			    lpBufferEffect->GetBufferPointer(),
			    lpBufferEffect->GetBufferSize(),
			    NULL, NULL,
			    0,
			    NULL, &m_pEffect, &lpErrors);

	// Errors...
	if(FAILED(hr)) {
	    if(lpErrors) {
		m_strErrors += (char*) lpErrors->GetBufferPointer();
		SAFE_RELEASE(lpErrors);
	    }

	    m_strErrors += "Unable to create effect from compiled ";
	    m_strErrors += filename;
	}
    }

    if(SUCCEEDED(hr)) {
        m_pEffect->GetDesc(&m_EffectDesc);
	hr = ParseParameters(lpEffectCompiler);
    }

    SAFE_RELEASE(lpErrors);
    SAFE_RELEASE(lpBufferEffect);
    SAFE_RELEASE(lpEffectCompiler);
    return hr;
}