Cartesian coordinates to Barycentric coordinates function giving unexpected behaviour

  aabb, c++, graphics

I am trying to see if a point is within a triangle in which it’s 3 points are in cartesian space. I used bresenham to outline the coordinates for you, all of that area should be filled with white pixels and that area only. I am using tinyrenderer https://github.com/ssloy/tinyrenderer/wiki/Lesson-2:-Triangle-rasterization-and-back-face-culling as a guideline. I converted his stuff from his setup to mine.

void computeTriangle(Vec2i a, Vec2i b, Vec2i c, TGAImage &image, TGAColor color) {
    //find bounding box dimensions
    int maxX = a.x;
    int maxY = a.y;
    int minX = a.x;
    int minY = a.y;
    
    //max coordinate
    if (maxX <= b.x) {
        maxX = b.x;
    }
    if (maxX <= c.x) {
        maxX = c.x;
    }
    
    if (maxY <= b.y) {
        maxY = b.y;
    }
    if (maxY <= c.y) {
        maxY = c.y;
    }
    
    //min coordinate
    if (minX >= b.x) {
        minX = b.x;
    }
    if (minX >= c.x) {
        minX = c.x;
    }
    
    if (minY >= b.y) {
        minY = b.y;
    }
    if (minY >= c.y) {
        minY = c.y;
    }
    
    minX--;
    minY--;
    maxX++;
    maxY++;
    //bound loop
    for (int pX=minX; pX<=maxX; pX++) {
        for (int pY=minY; pY<=maxY; pY++) {
            Vec3f u = cross(Vec3f(c.x - a.x, b.x - a.x, a.x - pX), Vec3f(c.y - a.y, b.y - a.y, a.y - pY));
            Vec3f bcScreen;
            if (std::abs(u.z)<1) {
                bcScreen = Vec3f(-1,1,1);
            } else {
            bcScreen = Vec3f(1.f-(u.x+u.y)/u.z, u.y/u.z, u.x/u.z);
            }
            if (bcScreen.x<0 || bcScreen.y<0 || bcScreen.z<0) {
                image.set(pX, pY,color);
            }
        }
    }
}

Picture of the rendered image

Source: Windows Questions C++

LEAVE A COMMENT