Created
June 4, 2013 18:21
-
-
Save gszauer/5708228 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Building a 3d game engine in c++ by brian hook | |
// Constructor | |
void Triangle(vertex a, vertex b, vertex c, color) { | |
// Local cache variables | |
int x1 = a.x; | |
int x2 = b.x; | |
int x3 = c.x; | |
int y1 = a.y; | |
int y2 = b.y; | |
int y3 = c.y; | |
int tmp; | |
// Sort from top to bottom | |
if (y3 < y1) { | |
tmp = y3; | |
y3 = y1; | |
y1 = tmp; | |
tmp = x3; | |
x3 = x1; | |
x1 = tmp; | |
} | |
if (y2 < y1) { | |
tmp = y2; | |
y2 = y1; | |
y1 = tmp; | |
tmp = x2; | |
x2 = x1; | |
x1 = tmp; | |
} | |
if (y3 < y2) { | |
tmp = y3; | |
y3 = y2; | |
y2 = tmp; | |
tmp = x3; | |
x3 = x2; | |
x2 = tmp; | |
} | |
// If the triangle has no horizontal edges split it into two triangles | |
if (y2 != y1 && y3 != y1 && y3 != y2) { | |
int xn; | |
// find new x value | |
xn = (x3 - x1) * ((y2 - y1) / (y3 - y1)) + x1; | |
// Draw sub triangles | |
if (xn < x2) { | |
DrawTriangle(x1, y1, xn, y2, x2, y2, color); | |
DrawTriangle(x3, y3, x2, y2, xn, y2, color); | |
} else { | |
DrawTriangle(x1, y1, x2, y2, xn, y2, color); | |
DrawTriangle(x3, y3, y2, y2, xn, y2, color); | |
} | |
} | |
// Top is flat | |
else if (y1 == y2) { | |
if (x1 < x2) | |
DrawTriangle(x3, y3, x2, y2, x1, y2, color); | |
else | |
DrawTriangle(x3, y3, x1, y2, x2, y2, color); | |
} | |
// Bottom is flat | |
else if (y2 == y3) { | |
if (x2 < x3) | |
DrawTriangle(x1, y1, x2, y2, x3, y2, color); | |
else | |
DrawTriangle(x1, y1, x3, y2, x2, y2, color); | |
} | |
} | |
// Actually rasterise the triangle | |
void DrawTriangle(int x1, y1, x2, y2, x3, y3, color) { | |
float dx_left, dx_right; | |
float curx_left, curx_right; | |
float height = y(2 or 3) - y1; | |
// make sure height is not 0 | |
if (height == 0) | |
return; | |
// determine the slope for the left and right sides | |
dx_left = (x2 - x1) / height; | |
dx_right = (x3 - x1) / height; | |
curx_left = curx_right = x1; | |
if (y1 < y(2 or 3)) { | |
for (int y = y1; y < y(2 or 3); ++y) { | |
DrawLine(curx_left, curx_right, y, color); | |
// adjust x coords | |
curx_left += dx_left; | |
curx_right += dx_right; | |
} | |
} else { | |
for (int y = y1; y >= y(2 r 3); --y) { | |
DrawLine(curx_left, curx_right, y, color); | |
curx_left -= dx_left; | |
curx_right -= dx_right; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment