Vector3f RayColor(const Ray& ray, Scene& scene, int depth=0, bool test=false){ HitInfo closest_hp; closest_hp.t = FLT_MAX; closest_hp.objIdx = -1; //光线和球求交 for (int i = 0; i < scene.ObjectCount(); ++i) { HitInfo ht; bool bhit = scene.GetObjectPtr(i)->Hit(ray, ht); if (bhit) { if (ht.t > 0 && ht.t<closest_hp.t) { closest_hp = ht; closest_hp.objIdx = i; } } } //这里图省事,直接把光照参数写在这边 Vector3f lightpos(0.0, 4, 2); Vector3f lightAmbient(0.6, 0.6, 0.6); Vector3f lightDiffuse(1.0, 1.0, 1.0); Vector3f lightSpecular(1.0, 1.0, 1.0); if (closest_hp.objIdx != -1) { int idx = closest_hp.objIdx; Material mtl = scene._scene[idx].second; //环境光 Vector3f ambient = Vector3f(lightAmbient[0]* mtl._Ka[0], lightAmbient[1] * mtl._Ka[1], lightAmbient[2] * mtl._Ka[2]); Vector3f color = ambient; bool isShadow = false; //shadow ray 求交 Ray shadow_ray(closest_hp.position, lightpos - closest_hp.position); //请在以下部分加入对shadow ray是否被场景遮挡的判断,并对isShadow这个变量进行修改 //请在以上部分加入对shadow ray是否被场景遮挡的判断,并对isShadow这个变量进行修改 Vector3f eyedir = (Vector3f(0, 0, 0) - closest_hp.position).normalized(); if(!isShadow) //如果不是阴影,继续计算 { //漫反射 Vector3f lightdir = (lightpos - closest_hp.position).normalized(); float coscoef = lightdir.dot(closest_hp.normal); if (coscoef < 0) coscoef = 0; Vector3f diffuse = Vector3f(0.8* mtl._Kd[0] * coscoef, 0.8 * mtl._Kd[1] * coscoef, 0.8 * mtl._Kd[2] * coscoef); Vector3f half = (eyedir + shadow_ray.Direction().normalized()).normalized(); float specularcoef = half.dot(closest_hp.normal); if (specularcoef < 0) specularcoef = 0; else specularcoef = pow(specularcoef, mtl._shiness); Vector3f specular = Vector3f(lightSpecular[0]* mtl._Ks[0] * specularcoef, lightSpecular[1] * mtl._Ks[1] * specularcoef, lightSpecular[2] * mtl._Ks[2] * specularcoef); color += diffuse + specular; }漫反射和镜面反射递归函数具体代码是什么
时间: 2024-03-01 08:54:17 浏览: 29
以下是漫反射和镜面反射的递归函数代码:
```
if (depth >= max_depth) return color;
if (mtl._Kr.norm() == 0) {
//漫反射
Vector3f lightdir = (lightpos - closest_hp.position).normalized();
float coscoef = lightdir.dot(closest_hp.normal);
if (coscoef < 0) coscoef = 0;
Vector3f diffuse = Vector3f(mtl._Kd[0] * coscoef, mtl._Kd[1] * coscoef, mtl._Kd[2] * coscoef);
color += diffuse;
} else {
//镜面反射
Vector3f eyedir = (Vector3f(0, 0, 0) - closest_hp.position).normalized();
Vector3f reflect_dir = (eyedir - 2 * closest_hp.normal.dot(eyedir) * closest_hp.normal).normalized();
Ray reflect_ray(closest_hp.position, reflect_dir);
HitInfo reflect_hp;
bool bhit_reflect = scene.Intersect(reflect_ray, reflect_hp);
if (bhit_reflect) {
Material mtl_reflect = scene._scene[reflect_hp.objIdx].second;
color += mtl._Kr.cwiseProduct(RayColor(reflect_ray, scene, depth + 1));
} else {
color += mtl._Kr.cwiseProduct(Vector3f(0, 0, 0));
}
}
```
其中,`max_depth` 为递归深度的最大值,`mtl._Kr` 表示材质的镜面反射系数,若其为 0 则进行漫反射计算,否则进行镜面反射计算。在进行镜面反射计算时,需要计算反射光线,并进行递归计算反射光线的颜色,并将其与当前颜色相加。