Skip to content

Instantly share code, notes, and snippets.

@brht0
Created March 25, 2022 05:57
Show Gist options
  • Save brht0/90e0007180db0385ec548a4582d3f682 to your computer and use it in GitHub Desktop.
Save brht0/90e0007180db0385ec548a4582d3f682 to your computer and use it in GitHub Desktop.
Triangle fill and line draw algorithms with SDL2 using SDL_Surface
// Untested code, but should work with some tweaks (more or less)
struct Point{
double x, y;
};
struct Line{
Point p1, p2;
};
void DrawLine(Line l, SDL_Surface* dst, Uint32 color){
Uint32* pixels = (Uint32*)dst->pixels;
int width = dst->w;
int height = dst->h;
// differences
double dx = l.p2.x - l.p1.x;
double dy = l.p2.y - l.p1.y;
// slope
double k = dy / dx;
// based on slope value, fill pixel-by-pixel either horisontally or vertically
if(abs(k) <= 1.0){
if(l.p1.x > l.p2.x){
Point temp = l.p1;
l.p1 = l.p2;
l.p2 = temp;
}
// fill horisontally
for(int x=l.p1.x; x<l.p2.x; x++){
int y = l.p1.y + (x - l.p1.x) * k;
if(x >= 0 && x < width && y >= 0 && y < height)
pixels[y*width + x] = color;
}
}
else{
if(l.p1.y > l.p2.y){
Point temp = l.p1;
l.p1 = l.p2;
l.p2 = temp;
}
// fill vertically
for(int y=l.p1.y; y<l.p2.y; y++){
int x = l.p1.x + (y - l.p1.y) / k;
if(x >= 0 && x < width && y >= 0 && y < height)
pixels[y*width + x] = color;
}
}
}
void DrawHorisontalLine(int y, int x1, int x2, SDL_Surface* dst, Uint32 color){
Uint32* pixels = (Uint32*)dst->pixels;
if(x2 < x1)
swap(x2, x1);
// clamp co-ordinates to screen size
if(x1 < 0) x1 = 0;
if(x2 >= dst->w) x2 = dst->w - 1;
for(int x=x1; x<x2; x++){
pixels[y*dst->w+x] = color;
}
}
void FillTriangle(Point p1, Point p2, Point p3, SDL_Surface* dst, Uint32 color){
// sort points by height
if(p3.y < p2.y) swap(p3, p2);
if(p2.y < p1.y) swap(p2, p1);
if(p3.y < p2.y) swap(p3, p2);
// calculate differences
double dx1 = p3.x - p1.x;
double dx2 = p2.x - p1.x;
double dx3 = p3.x - p2.x;
double dy1 = p3.y - p1.y;
double dy2 = p2.y - p1.y;
double dy3 = p3.y - p2.y;
// line slopes
double k1 = dy1 / dx1;
double k2 = dy2 / dx2;
double k3 = dy3 / dx3;
// draw line by line from top to bottom
for(int y=p1.y; y<p3.y; y++){
int x1 = (y - p1.y) / k1 + p1.x;
int x2;
// determine if lower or upper half
if(y < p2.y){
x2 = (y - p1.y) / k2 + p1.x;
}else{
x2 = (y - p2.y) / k3 + p2.x;
}
DrawHorisontalLine(y, x1, x2, dst, color);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment