是否在三角形内
static bool insideTriangle(int x, int y, const Vector3f* _v)
{
// TODO : Implement this function to check if the point (x, y) is inside the triangle represented by _v[0], _v[1], _v[2]
Vector2f v0(_v[0].x(), _v[0].y());
Vector2f v1(_v[1].x(), _v[1].y());
Vector2f v2(_v[2].x(), _v[2].y());
Vector2f point(x, y);
Vector2f AB = v1 - v0;
Vector2f CA = v0 - v2;
Vector2f AP = point - v0;
Vector2f BC = v2 - v1;
Vector2f BP = point - v1;
float crossAB_AP = crossProduct(AB, AP);
float crossAC_AP = crossProduct(CA, AP);
float crossBC_BP = crossProduct(BC, BP);
// 检查点是否在边 AB 和 AC 的同一侧
bool isSameSideAB = (crossAB_AP >= 0.0f);
bool isSameSideAC = (crossCA_AP >= 0.0f);
// 如果点不在 AB 和 AC 的同一侧,则点不在三角形内
if (isSameSideAB != isSameSideAC) return false;
// 如果点不在 BC 的同一侧(与 AB 和 AC 相同的一侧),则点不在三角形内
if (isSameSideAB != (crossBC_BP >= 0.0f)) return false;
if (point.isApprox(v0) || point.isApprox(v1) || point.isApprox(v2))
{
return true;
}
return true;
}
光栅化
void rst::rasterizer::rasterize_triangle(const Triangle& t) {
auto v = t.toVector4();
// TODO : Find out the bounding box of current triangle.
// iterate through the pixel and find if the current pixel is inside the triangle
// If so, use the following code to get the interpolated z value.
//auto[alpha, beta, gamma] = computeBarycentric2D(x, y, t.v);
//float w_reciprocal = 1.0/(alpha / v[0].w() + beta / v[1].w() + gamma / v[2].w());
//float z_interpolated = alpha * v[0].z() / v[0].w() + beta * v[1].z() / v[1].w() + gamma * v[2].z() / v[2].w();
//z_interpolated *= w_reciprocal;
// TODO : set the current pixel (use the set_pixel function) to the color of the triangle (use getColor function) if it should be painted.
rst::BoundingBox2D bbox;
bbox = createBoundingBox2D(v);
for (int x = bbox.minX; x < bbox.maxX; ++x)
{
for (int y = bbox.minY; y < bbox.maxY; ++y)
{
bool isInside = insideTriangle(x,y, t.v);
if (isInside)
{
auto[alpha, beta, gamma] = computeBarycentric2D(x, y, t.v);
float w_reciprocal = 1.0/(alpha / v[0].w() + beta / v[1].w() + gamma / v[2].w());
float z_interpolated = alpha * v[0].z() / v[0].w() + beta * v[1].z() / v[1].w() + gamma * v[2].z() / v[2].w();
z_interpolated *= w_reciprocal;
std::size_t index = static_cast<std::size_t>(get_index(x, y));
Eigen::Vector3f point(x,y,z_interpolated);
if (index < depth_buf.size() && z_interpolated < depth_buf[index])
{
Eigen::Vector3f interpolated_color = t.getColor();
depth_buf[index] = z_interpolated;
set_pixel(point, interpolated_color);
}
}
}
}
}
./rasterizer aa.png