摸索了很久,總算有點(diǎn)理清Alpha混合的原理。
關(guān)于Alpha混合,最主要的就是要設(shè)定好,混合源。然后在渲染時(shí),即時(shí)開啟Alpha混合效果,用完后再即時(shí)關(guān)閉(之所以需要關(guān)閉,是因?yàn)樗挠?jì)算量太大,關(guān)閉可節(jié)省資源)
設(shè)定Alpha混合源:
m_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
m_pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
m_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
m_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
開關(guān)Alpha混合效果:
m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true/*false*/);
//創(chuàng)建對(duì)象
this->InitTeapot();
this->InitTeapotMaterial();
this->InitBkGndQuad();
this->InitBkGndMaterial();
this->InitBkGndTexture();
this->InitDirLight();
//更改渲染狀態(tài)
m_pDevice->SetRenderState(D3DRS_NORMALIZENORMALS, true);
m_pDevice->SetRenderState(D3DRS_SPECULARENABLE, true);
//參考code:
//設(shè)置渲染狀態(tài)
m_pDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
m_pDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
m_pDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
m_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE); //此可設(shè)置成源處貼圖的alpha通道(當(dāng)前源自材質(zhì))
m_pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
m_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
m_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
m_pDevice->SetLight(0, &m_DirLight);// 燈光也是非必須的。如果沒加。需使對(duì)象自發(fā)光,要不看不到效果。
m_pDevice->LightEnable(0, true);
//set camera position and view&projection matrix.
...
// onrender event
m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
m_pDevice->SetMaterial(&m_TeapotMtrl);
m_pDevice->SetTexture(0, 0);//這句應(yīng)該是非必須的。但最好加。
m_pTeapot->DrawSubset(0);
m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
想要理解Alpha混合的原理,其實(shí)還有一個(gè)很重要的概念需要理清。就是3D空間中物體渲染的先后順序以及物體離攝像機(jī)的遠(yuǎn)近位置。正常來說,Alpha混合,在實(shí)現(xiàn)時(shí),需要首先繪制不需要混合的物體,而且該物體往往離攝像機(jī)較遠(yuǎn)。然后才繪制離攝像頭近的,且需要融合的物體。否則有可能會(huì)出現(xiàn)不可理喻的現(xiàn)象。(比如:遠(yuǎn)處物體居然會(huì)遮擋住近處的物體)。