我正在开发一个延迟着色程序,现在我必须在场景中设置 50 种不同的灯光。为此,我使用以下代码随机生成其属性(位置、漫反射颜色、镜面反射颜色):
void FBORender::BuildLights()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0.0, 0.1);
for (int i = 0; i < NUM_LIGHTS; i++)
{
float dc_r = (float) dis(gen);
float dc_g = (float) dis(gen);
float dc_b = (float) dis(gen);
printf("%f\n", dc_r);
float lp_x = (float)(rand() % 40 - 20);
float lp_y = (float)(rand() % 100 + 10);
float lp_z = (float)(rand() % 40 - 20);
DC[i * NUM_LIGHTS] = dc_r;
DC[i * NUM_LIGHTS + 1] = dc_g;
DC[i * NUM_LIGHTS + 2] = dc_b;
LP[i * NUM_LIGHTS] = lp_x;
LP[i * NUM_LIGHTS + 1] = lp_y;
LP[i * NUM_LIGHTS + 2] = lp_z;
}
}
但是,我不太确定如何使用多盏灯进行照明。有人说环境光应该等于漫反射光,而镜面光应该是白色的。
调整我必须执行 Phong 照明的着色器,我有这个:
#version 410 core
#define numLights 5
uniform sampler2D tDiffuse;
uniform sampler2D tPosition;
uniform sampler2D tNormals;
uniform vec4 specularColor;
uniform vec3 diffuseColor[numLights];
uniform vec3 vLightPosition[numLights];
in vec2 texCoord;
out vec4 fragColor;
void main( void )
{
vec3 tex = texture( tDiffuse, texCoord.st ).xyz;
vec3 vPosition = texture( tPosition, texCoord.st ).xyz;
vec3 vNormal = normalize( texture( tNormals, texCoord.st ).xyz * 2 - 1 );
vec3 vVaryingNormal = vNormal;
for (int i = 0; i < numLights; i++)
{
vec3 vVaryingLightDir = normalize( vLightPosition[i] - vPosition );
float diff = max( 0.0, dot( normalize( vVaryingNormal ), normalize( vVaryingLightDir ) ) );
vec4 partialColor = diff * vec4(diffuseColor[i], 1.0);
partialColor = vec4( mix( partialColor.rgb, tex, 0.5 ), partialColor.a );
partialColor += vec4( diffuseColor[i], 1.0 );
vec3 vReflection = normalize( reflect( -normalize( vVaryingLightDir ), normalize( vVaryingNormal )));
float spec = max( 0.0, dot( normalize( vVaryingNormal ), vReflection ));
if( diff != 0 )
{
float fSpec = pow( spec, 128.0 );
partialColor.rgb += vec3( fSpec, fSpec, fSpec );
}
fragColor += partialColor;
}
}
但是,我得到了丑陋的结果(如果不是错的话),如下图所示:
这个结果只使用了 2 盏灯。由于我必须使用 50,我认为我将看到的只是一个白屏......