您的位置:首页 > 其它

DirectX 10 学习笔记7:环境光

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

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

[code]....


float4 ambientColor;


....

[/code]

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

[code]...


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


color = ambientColor;


...

[/code]

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

[code]...


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);


....

[/code]

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

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

[code]ID3D10EffectVectorVariable* m_ambientColorPtr;

[/code]

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

[code]void Render(ID3D10Device*, int, D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D10ShaderResourceView*, D3DXVECTOR3, D3DXVECTOR4, D3DXVECTOR4);


void SetShaderParameters(D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, ID3D10ShaderResourceView*, D3DXVECTOR3, D3DXVECTOR4, D3DXVECTOR4);

[/code]

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

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

[/code]

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

[code]m_ambientColorPtr->SetFloatVector((float*)&ambientColor);

[/code]

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

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

[code]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);

[/code]

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

[code]m_LightShader->Render(m_D3D->GetDevice(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTexture(),


m_Light->GetDirection(), m_Light->GetAmbientColor(), m_Light->GetDiffuseColor());

[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: