作为初学者的学习体验,我一直在尝试用 Java 编写一个非常简单的光线追踪器。到目前为止,我可以渲染环境和朗伯着色,并且我一直在尝试添加镜面高光和反射,但没有成功。
我检查过的每个网站都提到了环境 + 漫反射 + 镜面反射方程,但我不明白如何为每个像素添加某个镜面反射值到 R、G 和 B 是假设添加白色高光。
我也很难弄清楚如何将反射颜色和对象颜色与阴影混合。
编辑:经过一些调整,这里是新的结果
我的引擎类代码如下所示:
Color color = new Color(0, 0, 0);
Color reflected_color = new Color(0, 0, 0);
Sphere obj = (Sphere) this.find_nearest_obj(ray, scene).get(0);
Vector l = null;
double obj_dist = (double) this.find_nearest_obj(ray, scene).get(1);
if (obj == null)
return color;
for (Object o : scene.getObjects()) {
if (o instanceof Vector) {
l = (Vector) o;
}
}
/*
* Calculate specific fragment elements
*/
Vector hit_pos = ray.getPoint().add(ray.getDir().mult(obj_dist));
Vector normal = hit_pos.sub(obj.getCenter());
Ray reflected_ray = get_reflected_ray(normal, ray, hit_pos, l);
// Vector view = normal.mult(2).mult(-1 * normal.dot(ray.getDir()));
Vector view = scene.getCamera().sub(hit_pos);
if (obj.isReflective() && ctrl < 5) {
ctrl++;
reflected_color = ray_trace(reflected_ray, scene);
// TODO: recursive reflection implementation
}
color = colorAt(obj, scene, normal, reflected_color, view, reflected_ray); // return fragment color
return color;
}
public List<Object> find_nearest_obj(Ray ray, Scene scene) {
double obj_dist = 0;
Sphere obj_hit = null;
List<Object> pair = new ArrayList<Object>();
for (Object s : scene.getObjects()) { // Find scene objects
if (s instanceof Sphere) {
double dist = ((Sphere) s).intersects(ray);
if (dist > 0 && (obj_hit == null || dist < obj_dist)) {
obj_dist = dist;
obj_hit = (Sphere) s;
}
}
}
pair.add(obj_hit);
pair.add(obj_dist);
return pair;
}
public Ray get_reflected_ray(Vector normal, Ray ray, Vector hit_pos, Vector l) {
return new Ray(new Point(hit_pos.x, hit_pos.y, hit_pos.z),
ray.getDir().add(normal.mult(2).mult(-1 * normal.dot(ray.getDir()))));
// return new Ray(new Point(hit_pos.x, hit_pos.y, hit_pos.z), l.sub(normal.mult(2).mult(normal.dot(l))));
}
public Color colorAt(Sphere obj, Scene scene, Vector normal, Color reflected_color, Vector view, Ray reflected) {
Vector l = null;
Vector frag_color = null;
for (Object o : scene.getObjects()) {
if (o instanceof Vector) {
l = (Vector) o;
if (l != null) {
double diffuse = l.norm().dot(normal.norm());
double specular = Math.pow(view.dot(reflected.getDir()), specular_coef);
if (diffuse < 0)
diffuse = 0;
if (specular < 0)
specular = 0;
frag_color = (obj.getColor().add(reflected_color)).mult(ambient_control * ambient_coef + (1 - ambient_coef) * diffuse + specular);
}
}
}
return new Color(frag_color.x, frag_color.y, frag_color.z);
}
}