DirectX 10 学习笔记7:环境光

本节用一种简单的方式模拟环境光:在pixel shader的开始部分,把所有的像素值设置为环境光的值。此后所有的操作都把新的值加在环境光的颜色值上。以此保证在渲染的场景中的最小值为环境光的颜色。

首先是shader中的改变。由于引入了环境光,所以需要添加一个对应的全局变量:

....
float4 ambientColor;
....

 

然后在pixel shader中,首先把像素的颜色设置为环境光的颜色:

...
// Set the default output color to the ambient light value for all pixels.
color = ambientColor;
...

 

至于该像素点是否要加上漫射光的影响,要检查该点法向量与漫射光方向的夹角,即漫射光是否能照到该点:

...
lightIntensity = saturate(dot(input.normal, lightDir));
if(lightIntensity > 0.0f)
{
    // Determine the final diffuse color based on the diffuse color and the amount of light intensity.
    color += (diffuseColor * lightIntensity);
}
// Saturate the final light color.
color = saturate(color);
....

负责加载shader以及初始化shader中全局变量的LightShaderClass也要进行相应改动:

在LightShaderClass中添加访问shader中环境光的私有指针:

ID3D10EffectVectorVariable* m_ambientColorPtr;

由于添加了环境光,所以Render和SetParameters的参数列表都要改变:

void Render(ID3D10Device*, int, D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D10ShaderResourceView*, D3DXVECTOR3, D3DXVECTOR4, D3DXVECTOR4);
void SetShaderParameters(D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D10ShaderResourceView*, D3DXVECTOR3, D3DXVECTOR4, D3DXVECTOR4);

在InitializeShader中,添加访问shader中环境光变量的代码:

m_ambientColorPtr = m_effect->GetVariableByName("ambientColor")->AsVector();

SetParameters函数中添加设置环境光的代码:

m_ambientColorPtr->SetFloatVector((float*)&ambientColor);

光照类也要添加环境光对应的成员变量以及相应的set和get函数。

在视图类初始化时,设置环境光、漫射光以及光照方向:

m_Light->SetAmbientColor(0.15f, 0.15f, 0.15f, 1.0f);
m_Light->SetDiffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
m_Light->SetDirection(1.0f, 0.0f, 0.0f);

OnPaint函数中,按照新的参数列表调用LightShaderClass的Render函数:

m_LightShader->Render(m_D3D->GetDevice(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTexture(),
                  m_Light->GetDirection(), m_Light->GetAmbientColor(), m_Light->GetDiffuseColor());

posted on 2013-01-24 20:44  youthlion  阅读(694)  评论(0编辑  收藏  举报

导航