maskedLine

Version:

1.0

Added on:

11 Dec 2017 04:33

Tags:

Description:
JJ2+ has the maskedHLine and maskedVLine functions (and their derivatives) but those are only useful if you're checking a straight line. This function takes two arbitrary points (x0, y0) and (x1, y1) as arguments and checks if any pixel on a straight line between them is masked.

Note that the line is one pixel thick, so there is no guarantee that a rabbit will fit through whatever gap you're testing.
  1. /*
  2.  * Check whether any pixel on a line between two positions is masked
  3.  *
  4.  * Returns true if masked pixel is found, false if not.
  5.  */
  6. bool maskedLine(int x0, int y0, int x1, int y1, int layer = 4) {
  7.   int x2;
  8.   int y2;
  9.  
  10.   //straight lines
  11.   if(x0 == x1 || y0 == y1) {
  12.     if(y0 == y1) {
  13.       if(x0 > x1) {
  14.         x2 = x1; x1 = x0; x0 = x2; //swap
  15.       }
  16.       for(int x = x0; x < x1; x += 1) {
  17.         if(jjLayers[layer].maskedPixel(x, y0)) {
  18.           return true;
  19.         }
  20.       }
  21.       return false;
  22.     }
  23.  
  24.     if (y0 > y1) {
  25.       y2 = y1; y1 = y0; y0 = y2; //swap
  26.     }
  27.    
  28.     for(int y = y0; y < y1; y += 1) {
  29.       if(jjLayers[layer].maskedPixel(x0, y)) {
  30.         return true;
  31.       }
  32.     }
  33.     return true;
  34.   }
  35.  
  36.  
  37.   //sloped lines
  38.   bool steep = (abs(y1 - y0) > abs(x1 - x0));
  39.  
  40.   if (steep) {
  41.     x2 = x0; x0 = y0; y0 = x2; //swap
  42.     y2 = x1; x1 = y1; y1 = y2; //swap
  43.   }
  44.  
  45.   if (x0 > x1) {
  46.     x2 = x1; x1 = x0; x0 = x2; //swap
  47.     y2 = y1; y1 = y0; y0 = y2; //swap
  48.   }
  49.  
  50.   float dx = x1 - x0;
  51.   float dy = abs(y1 - y0);
  52.  
  53.   float error = dx / 2.0f;
  54.   int ystep = (y0 < y1) ? 1 : -1;
  55.  
  56.   int y = int(y0);
  57.   int max_x = int(x1);
  58.  
  59.   for(int x = int(x0); x < max_x; x += 1) {
  60.     if (steep) {
  61.       if(jjLayers[layer].maskedPixel(y, x)) {
  62.         return true;
  63.       }
  64.     } else {
  65.       if(jjLayers[layer].maskedPixel(x, y)) {
  66.         return true;
  67.       }
  68.     }
  69.  
  70.     error -= dy;
  71.     if (error < 0) {
  72.       y += ystep;
  73.       error += dx;
  74.     }
  75.   }
  76.  
  77.   return false;
  78. }