Loading

Paste #pmxvuic0n

  1. Town *AirportGetNearestTownKdTree(const AirportSpec *as, const TileIterator &it)
  2. {
  3.     Town *nearest = NULL;
  4.     if (Town::GetNumItems() == 0) return nearest;
  5.  
  6. //  uint add = as->size_x + as->size_y - 2; // CalcClosestTownFromTile can differ from DistanceManhattan by this much
  7.     uint mindist = UINT_MAX - 1; // prevent overflow
  8.  
  9.     TileIterator *copy = it.Clone();
  10.     for (TileIndex cur_tile = *copy; cur_tile != INVALID_TILE; cur_tile = ++*copy) {
  11.         Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
  12.         if (t == NULL) continue;
  13.  
  14.         uint dist = DistanceManhattan(t->xy, cur_tile);
  15.         if (dist == mindist && t->index < nearest->index) nearest = t;
  16.         if (dist < mindist) {
  17.             nearest = t;
  18.             mindist = dist;
  19.         }
  20.     }
  21.     delete copy;
  22.  
  23.     return nearest;
  24. }
  25.  
  26. Town *AirportGetNearestTownForAllTowns(const AirportSpec *as, const TileIterator &it)
  27. {
  28.     Town *t, *nearest = NULL;
  29.     uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
  30.     uint mindist = UINT_MAX - add; // prevent overflow
  31.     FOR_ALL_TOWNS(t) {
  32.         if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
  33.             TileIterator *copy = it.Clone();
  34.             uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
  35.             delete copy;
  36.             if (dist < mindist) {
  37.                 nearest = t;
  38.                 mindist = dist;
  39.             }
  40.         }
  41.     }
  42.  
  43.     return nearest;
  44. }
  45.  
  46. /**
  47.  * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
  48.  * If two towns have the same distance, town with lower index is returned.
  49.  * @param as airport's description
  50.  * @param it An iterator over all airport tiles
  51.  * @return nearest town to airport
  52.  */
  53. Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
  54. {
  55.     assert(AirportGetNearestTownForAllTowns(as, it) == AirportGetNearestTownKdTree(as, it));
  56.     return AirportGetNearestTownKdTree(as, it);
  57. }

Comments