Skip to content

Instantly share code, notes, and snippets.

@rubenvanassche
Created May 23, 2013 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubenvanassche/5638930 to your computer and use it in GitHub Desktop.
Save rubenvanassche/5638930 to your computer and use it in GitHub Desktop.
void DrawTriangular::calculatePoints(Vector3D point1, Vector3D point2, Vector3D point3, img::Color color){
double oneZ = 1/(3*point1.z) + 1/(3*point2.z) + 1/(3*point3.z);
//project those points
this->projectPoint(point1);
this->projectPoint(point2);
this->projectPoint(point3);
double xG = (point1.x + point2.x + point3.x)/3;
double yG = (point1.y + point2.y + point3.y)/3;
int yMin = roundToInt(std::min(std::min(point1.y, point2.y), point3.y) + 0.5);
int yMax = roundToInt(std::max(std::max(point1.y, point2.y), point3.y) - 0.5);
//std::cout << "yMin " << yMin << " yMax" << yMax << std::endl;
if(yMin == yMax){
// No calculation possible, stop at this moment
return;
}
double posInfinity = std::numeric_limits<double>::infinity();
double negInfinity = -std::numeric_limits<double>::infinity();
//AB -> point1 - point2
//BC -> point2 - point3
//CA -> point3 - point1
// our lines
// Now start looping between YMin and YMax
for(int i = yMin;i <= yMax;i++){
double XlAB = posInfinity;
double XlCA = posInfinity;
double XlBC = posInfinity;
double XrAB = negInfinity;
double XrCA = negInfinity;
double XrBC = negInfinity;
if((i-point1.y)*(i-point2.y) <= 0 and point1.y != point2.y){
XlAB = point1.x + (point2.x - point1.x)*( (i-point1.y) / (point2.y-point1.y));
XrAB = point1.x + (point2.x - point1.x)*( (i-point1.y) / (point2.y-point1.y));
}
if((i-point2.y)*(i-point3.y) <= 0 and point2.y != point3.y){
XlBC = point2.x + (point3.x - point2.x)*( (i-point2.y) / (point3.y-point2.y));
XrBC = point2.x + (point3.x - point2.x)*( (i-point2.y) / (point3.y-point2.y));
}
if((i-point1.y)*(i-point3.y) <= 0 and point1.y != point3.y){
XlCA = point3.x + (point1.x - point3.x)*( (i-point3.y) / (point1.y-point3.y));
XrCA = point3.x + (point1.x - point3.x)*( (i-point3.y) / (point1.y-point3.y));
}
int Xl = roundToInt(std::min(std::min(XlAB, XlBC), XlCA));
int Xr = roundToInt(std::max(std::max(XrAB, XrBC), XrCA));
Vector3D u = point2 - point1;
Vector3D v = point3 - point1;
Vector3D w;
w.x = u.y*v.z - u.z*v.y;
w.y = u.z*v.x - u.x*v.z;
w.z = u.x*v.y - u.y*v.x;
double k = (w.x * point1.x) + (w.y * point1.y) + (w.z * point1.z);
double dzdx = w.x/(-d*k);
double dzdy = w.y/(-d*k);
for(int j = Xl;j < Xr;j++){
double pixelZValue = 1.0001*(1/oneZ) + (j-xG)*dzdx + (i-yG)*dzdy;
pixelZValue = 1/pixelZValue;
//do we need to draw?
if(buffer.redraw(j, i, pixelZValue)){
this->image(j, i) = color;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment