Triangle Rasterizing not working properly - Java

Viewed 94

I am trying to make triangle rasterization work, and it does not work properly (second link is image). I don't want to use any engines or libraries because I want to practice this a little bit.

This is the page where I got functions from:

The shape on top is the one I get using my functions and the second one is what I get when I use java.awt.Graphics.fillPolygon() method - or what it should look like:

img

I didn't include FillBottomTriangle and FillTopTriangle functions in code because they are copy-pasted from the site (first link). Also, I know code can be optimized, but this was only done to test if it works.

// This is not the entire while-true-loop, only part needed for this question
// This sorts points by their Y value since that's how rasterizing code works
for (int j = 0; j < 2; j++) {
    for (int k = 0; k < 2; k++) {
        if (fpoints[k][1] > fpoints[k + 1][1]) {

            int[] r = fpoints[k];
            fpoints[k] = fpoints[k + 1];
            fpoints[k + 1] = r;

         }
     }
 }

 // DRAW TRIANGLE
 if (fpoints[1][1] == fpoints[2][1]) FillBottomTriangle(g, fpoints[0], fpoints[1], fpoints[2]);
 else if (fpoints[0][1] == fpoints[1][1]) FillTopTriangle(g, fpoints[0], fpoints[1], fpoints[2]);
 else {
     int[] v4 = new int[] {
         (int)(fpoints[0][0] + ((float)(fpoints[1][1] - fpoints[0][1]) / (float)(fpoints[2][1] - fpoints[0][1])) * (fpoints[2][0] - fpoints[0][0])),
                        fpoints[1][1]
                };
     FillBottomTriangle(g, fpoints[0], fpoints[1], v4);
     FillTopTriangle(g, fpoints[1], v4, fpoints[2]);
 }

 Polygon poly = new Polygon();
 for (int j = 0; j < fpoints.length; j++) {
     poly.addPoint(fpoints[j][0], fpoints[j][1] + 128);
 }
 g.fillPolygon(poly);

Thank you.

EDIT: fpoints[n] is the point and fpoints[n][m] is the coordinate, i.e. fpoints[2][0] is X coordinate of point C of triangle.

0 Answers
Related