Skip to content

Instantly share code, notes, and snippets.

@bit-hack
Last active March 31, 2020 22:52
Show Gist options
  • Save bit-hack/6ad81944669ffcb62adef78f87f5691c to your computer and use it in GitHub Desktop.
Save bit-hack/6ad81944669ffcb62adef78f87f5691c to your computer and use it in GitHub Desktop.
a scanline rasterizer derivation
void span( float x0, float y0 )
{
// blah
}
void raster( vec2 point[3] )
{
std::array<mut::vec2, 3> p = {
point[0], point[1], point[2]
};
// sorting network for the vertices
if (p[2].y < p[1].y) std::swap(p[2], p[1]);
if (p[1].y < p[0].y) std::swap(p[1], p[0]);
if (p[2].y < p[1].y) std::swap(p[2], p[1]);
// triangles will be of either form:
//
// 0 0
// 1
// 1
// 2 2
//
// test point 1 on line 0->2 ?
//
// find the gradients (dx/dy)
const std::array<float, 3> d = {
(p[1].x - p[0].x) / (p[1].y - p[0].y),
(p[2].x - p[1].x) / (p[2].y - p[1].y),
(p[0].x - p[2].x) / (p[0].y - p[2].y),
};
// find y crossings
const float miny = floor(p[0].y + .5f) + .5f;
const float midy = p[1].y;
const float maxy = p[2].y;
// top half
draw::colour( 0x00FF00 );
float x0, x1;
float y = miny;
// calculate top half starting points
x0 = p[0].x + (y - p[0].y) * d[0];
x1 = p[2].x + (y - p[2].y) * d[2];
// top half
for (; y < midy; y += 1.f) {
span(x0, x1);
x0 += d[0];
x1 += d[2];
}
// calculate bottom half starting points
x0 = p[1].x + (y - p[1].y) * d[1];
x1 = p[2].x + (y - p[2].y) * d[2];
// bottom half
for (; y < maxy; y += 1.f) {
span(x0, x1);
x0 += d[1];
x1 += d[2];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment