【发布时间】:2019-10-21 03:28:30
【问题描述】:
在一个周末使用 Peter Shirley 的光线跟踪,我在尝试将球体渲染为红色时遇到了问题。我的数学似乎是准确的,但是它输出看起来像 2 个并排的球体并且还倾斜/拉伸,而不是场景中的 1 个球体。我怀疑它与光线投射的视野宽度有关,但不确定如何确认。代码如下:
main.cpp
#include "vectors.h"
#include "Geometry3D.h"
#include <fstream>
vec3 Color(const Ray& r, const Sphere& s) {
if (Raycast(s, r) != -1)
return vec3(1, 0, 0);
else
return vec3(0, 0, 0);
}
int main() {
const int WIDTH = 200;
const int HEIGHT = 100;
std::ofstream out;
out.open("image.ppm");
if (out.is_open()) {
out << "P3\n" << WIDTH << ' ' << HEIGHT << "\n255\n";
vec3 lowerLeftCorner(-2.0f, -1.0f, -1.0f);
vec3 horizontal(4.0f, 0.0f, 0.0f);
vec3 vertical(0.0, 2.0f, 0.0);
vec3 origin(0.0, 0.0, 0.0);
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
float u = float(i) / float(WIDTH);
float v = float(j) / float(HEIGHT);
Sphere s(vec3(0, 0, -5.0f), 1.0f);
Ray r(origin, lowerLeftCorner + (horizontal * u) + (vertical * v));
vec3 color = Color(r, s);
int ir = int(255.99f * color.x);
int ig = int(255.99f * color.y);
int ib = int(255.99f * color.z);
out << ir << ' ' << ig << ' ' << ib << '\n';
}
}
}
}
Geometry3D.h
#ifndef _GEOMETRY_3D_H
#define _GEOMETRY_3D_H
#include "vectors.h"
#include <cmath>
#include <cfloat>
typedef vec3 Point;
typedef struct Ray {
Point origin;
vec3 direction;
Ray() : direction(0.0f, 0.0f, 1.0f) { }
Ray(const Point& o, const vec3& d) : origin(o), direction(d) {
NormalizeDirection();
}
inline void NormalizeDirection() {
Normalize(direction);
}
} Ray;
typedef struct Sphere {
Point position;
float radius;
Sphere() : radius(1.0f) { }
Sphere(const Point& p, float r) : position(p), radius(r) { }
} Sphere;
float Raycast(const Sphere& sphere, const Ray& ray);
#endif
Geometry3D.cpp
#include "Geometry3D.h"
#include <iostream>
float Raycast(const Sphere& sphere, const Ray& ray) {
vec3 e = sphere.position - ray.origin;
float rSq = sphere.radius * sphere.radius;
float eSq = MagnitudeSq(e);
float a = Dot(e, ray.direction);
float bSq = eSq - (a * a);
float f = sqrt(rSq - bSq);
if (rSq - (eSq - (a * a)) < 0.0f)
return -1;
else if (eSq < rSq) {
return a + f;
}
return a - f;
}
这是输出:
感谢任何帮助。
【问题讨论】:
-
你确定不是简单的读/写图片文件的问题?看起来好像两行会被塞进一排。可能是设置宽度/高度或步幅有问题?
标签: c++ graphics raytracing