May there be any performance and/or code standard improvements on the following LineOfSight
code?
static List<Coordinate> getIntersects(Coordinate c1, Coordinate c2) {
// Bresenham's line algorithm from http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm#C.2B.2B
List<Coordinate> returningVector = new List<Coordinate>();
double y1 = c1.y, x1 = c1.x, y2 = c2.y, x2 = c2.x;
bool steep = (Math.Abs(y2 - y1) > Math.Abs(x2 - x1));
if(steep)
{
double _t;
_t = x1;
x1 = y1;
y1 = _t;
_t = x2;
x2 = y2;
y2 = _t;
}
if(x1 > x2)
{
double _t;
_t = x1;
x1 = x2;
x2 = _t;
_t = y1;
y1 = y2;
y2 = _t;
}
double dx = x2 - x1;
double dy = Math.Abs(y2 - y1);
double error = dx / 2.0f;
int ystep = (y1 < y2) ? 1 : -1;
int y = (int)y1;
int maxX = (int)x2;
for(int x=(int)x1; x<maxX; x++)
{
if(steep)
{
Coordinate tc = new Coordinate(y, x);
returningVector.Add(tc);
}
else
{
Coordinate tc = new Coordinate(x,y);
returningVector.Add(tc);
}
error -= dy;
if(error < 0)
{
y += ystep;
error += dx;
}
}
if(steep)
{
Coordinate tc = new Coordinate(y2, x2);
returningVector.Add(tc);
}
else
{
Coordinate tc = new Coordinate(x2,y2);
returningVector.Add(tc);
}
return returningVector;
}
static bool isObstacle(Coordinate c1, Coordinate c2, Coordinate c3) {
double heightOn_c3 = Math.Abs(((c1.height - c2.height) * Tools.distanceXY(c2, c3)) / Tools.distanceXY(c2, c1));
return (heightOn_c3 + c2.height) < c3.height;
}
public static bool calculateLOS(Coordinate c1, Coordinate c2, Map map) {
List<Coordinate> intersects = getIntersects(c1, c2);
for(int i=0; i<intersects.Count; i++) {
if(isObstacle(c1, c2, map.points[(int)intersects[i].x][(int)intersects[i].y].coordinates)){
return false;
}
}
return true;
}