viewport.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00029 #include "stdafx.h"
00030 #include "landscape.h"
00031 #include "viewport_func.h"
00032 #include "station_base.h"
00033 #include "waypoint_base.h"
00034 #include "town.h"
00035 #include "signs_base.h"
00036 #include "signs_func.h"
00037 #include "vehicle_base.h"
00038 #include "vehicle_gui.h"
00039 #include "blitter/factory.hpp"
00040 #include "strings_func.h"
00041 #include "zoom_func.h"
00042 #include "vehicle_func.h"
00043 #include "company_func.h"
00044 #include "core/alloc_func.hpp"
00045 #include "core/alloc_type.hpp"
00046 #include "core/smallvec_type.hpp"
00047 #include "waypoint_func.h"
00048 #include "window_func.h"
00049 #include "tilehighlight_func.h"
00050 #include "window_gui.h"
00051 #include "slope_func.h"
00052 #include "copy_paste.h"
00053 
00054 #include "table/strings.h"
00055 
00056 #include <map>
00057 
00058 Point _tile_fract_coords;
00059 
00060 struct StringSpriteToDraw {
00061   StringID string;
00062   Colours colour;
00063   int32 x;
00064   int32 y;
00065   uint64 params[2];
00066   uint16 width;
00067 };
00068 
00069 struct TileSpriteToDraw {
00070   SpriteID image;
00071   PaletteID pal;
00072   const SubSprite *sub;           
00073   int32 x;                        
00074   int32 y;                        
00075 };
00076 
00077 struct ChildScreenSpriteToDraw {
00078   SpriteID image;
00079   PaletteID pal;
00080   const SubSprite *sub;           
00081   int32 x;
00082   int32 y;
00083   int next;                       
00084 };
00085 
00087 struct ParentSpriteToDraw {
00088   SpriteID image;                 
00089   PaletteID pal;                  
00090   const SubSprite *sub;           
00091 
00092   int32 x;                        
00093   int32 y;                        
00094 
00095   int32 left;                     
00096   int32 top;                      
00097 
00098   int32 xmin;                     
00099   int32 xmax;                     
00100   int32 ymin;                     
00101   int32 ymax;                     
00102   int zmin;                     
00103   int zmax;                     
00104 
00105   int first_child;                
00106   bool comparison_done;           
00107 };
00108 
00110 enum FoundationPart {
00111   FOUNDATION_PART_NONE     = 0xFF,  
00112   FOUNDATION_PART_NORMAL   = 0,     
00113   FOUNDATION_PART_HALFTILE = 1,     
00114   FOUNDATION_PART_END
00115 };
00116 
00121 enum SpriteCombineMode {
00122   SPRITE_COMBINE_NONE,     
00123   SPRITE_COMBINE_PENDING,  
00124   SPRITE_COMBINE_ACTIVE,   
00125 };
00126 
00127 typedef SmallVector<TileSpriteToDraw, 64> TileSpriteToDrawVector;
00128 typedef SmallVector<StringSpriteToDraw, 4> StringSpriteToDrawVector;
00129 typedef SmallVector<ParentSpriteToDraw, 64> ParentSpriteToDrawVector;
00130 typedef SmallVector<ParentSpriteToDraw*, 64> ParentSpriteToSortVector;
00131 typedef SmallVector<ChildScreenSpriteToDraw, 16> ChildScreenSpriteToDrawVector;
00132 
00134 struct ViewportDrawer {
00135   DrawPixelInfo dpi;
00136 
00137   StringSpriteToDrawVector string_sprites_to_draw;
00138   TileSpriteToDrawVector tile_sprites_to_draw;
00139   ParentSpriteToDrawVector parent_sprites_to_draw;
00140   ParentSpriteToSortVector parent_sprites_to_sort; 
00141   ChildScreenSpriteToDrawVector child_screen_sprites_to_draw;
00142 
00143   int *last_child;
00144 
00145   SpriteCombineMode combine_sprites;               
00146 
00147   int foundation[FOUNDATION_PART_END];             
00148   FoundationPart foundation_part;                  
00149   int *last_foundation_child[FOUNDATION_PART_END]; 
00150   Point foundation_offset[FOUNDATION_PART_END];    
00151 };
00152 
00153 static ViewportDrawer _vd;
00154 
00155 TileHighlightData _thd;
00156 static TileInfo *_cur_ti;
00157 bool _draw_bounding_boxes = false;
00158 
00159 static Point MapXYZToViewport(const ViewPort *vp, int x, int y, int z)
00160 {
00161   Point p = RemapCoords(x, y, z);
00162   p.x -= vp->virtual_width / 2;
00163   p.y -= vp->virtual_height / 2;
00164   return p;
00165 }
00166 
00167 void DeleteWindowViewport(Window *w)
00168 {
00169   free(w->viewport);
00170   w->viewport = NULL;
00171 }
00172 
00185 void InitializeWindowViewport(Window *w, int x, int y,
00186   int width, int height, uint32 follow_flags, ZoomLevel zoom)
00187 {
00188   assert(w->viewport == NULL);
00189 
00190   ViewportData *vp = CallocT<ViewportData>(1);
00191 
00192   vp->left = x + w->left;
00193   vp->top = y + w->top;
00194   vp->width = width;
00195   vp->height = height;
00196 
00197   vp->zoom = zoom;
00198 
00199   vp->virtual_width = ScaleByZoom(width, zoom);
00200   vp->virtual_height = ScaleByZoom(height, zoom);
00201 
00202   Point pt;
00203 
00204   if (follow_flags & 0x80000000) {
00205     const Vehicle *veh;
00206 
00207     vp->follow_vehicle = (VehicleID)(follow_flags & 0xFFFFF);
00208     veh = Vehicle::Get(vp->follow_vehicle);
00209     pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
00210   } else {
00211     uint x = TileX(follow_flags) * TILE_SIZE;
00212     uint y = TileY(follow_flags) * TILE_SIZE;
00213 
00214     vp->follow_vehicle = INVALID_VEHICLE;
00215     pt = MapXYZToViewport(vp, x, y, GetSlopeZ(x, y));
00216   }
00217 
00218   vp->scrollpos_x = pt.x;
00219   vp->scrollpos_y = pt.y;
00220   vp->dest_scrollpos_x = pt.x;
00221   vp->dest_scrollpos_y = pt.y;
00222 
00223   w->viewport = vp;
00224   vp->virtual_left = 0;//pt.x;
00225   vp->virtual_top = 0;//pt.y;
00226 }
00227 
00228 static Point _vp_move_offs;
00229 
00230 static void DoSetViewportPosition(const Window *w, int left, int top, int width, int height)
00231 {
00232   FOR_ALL_WINDOWS_FROM_BACK_FROM(w, w) {
00233     if (left + width > w->left &&
00234         w->left + w->width > left &&
00235         top + height > w->top &&
00236         w->top + w->height > top) {
00237 
00238       if (left < w->left) {
00239         DoSetViewportPosition(w, left, top, w->left - left, height);
00240         DoSetViewportPosition(w, left + (w->left - left), top, width - (w->left - left), height);
00241         return;
00242       }
00243 
00244       if (left + width > w->left + w->width) {
00245         DoSetViewportPosition(w, left, top, (w->left + w->width - left), height);
00246         DoSetViewportPosition(w, left + (w->left + w->width - left), top, width - (w->left + w->width - left), height);
00247         return;
00248       }
00249 
00250       if (top < w->top) {
00251         DoSetViewportPosition(w, left, top, width, (w->top - top));
00252         DoSetViewportPosition(w, left, top + (w->top - top), width, height - (w->top - top));
00253         return;
00254       }
00255 
00256       if (top + height > w->top + w->height) {
00257         DoSetViewportPosition(w, left, top, width, (w->top + w->height - top));
00258         DoSetViewportPosition(w, left, top + (w->top + w->height - top), width, height - (w->top + w->height - top));
00259         return;
00260       }
00261 
00262       return;
00263     }
00264   }
00265 
00266   {
00267     int xo = _vp_move_offs.x;
00268     int yo = _vp_move_offs.y;
00269 
00270     if (abs(xo) >= width || abs(yo) >= height) {
00271       /* fully_outside */
00272       RedrawScreenRect(left, top, left + width, top + height);
00273       return;
00274     }
00275 
00276     GfxScroll(left, top, width, height, xo, yo);
00277 
00278     if (xo > 0) {
00279       RedrawScreenRect(left, top, xo + left, top + height);
00280       left += xo;
00281       width -= xo;
00282     } else if (xo < 0) {
00283       RedrawScreenRect(left + width + xo, top, left + width, top + height);
00284       width += xo;
00285     }
00286 
00287     if (yo > 0) {
00288       RedrawScreenRect(left, top, width + left, top + yo);
00289     } else if (yo < 0) {
00290       RedrawScreenRect(left, top + height + yo, width + left, top + height);
00291     }
00292   }
00293 }
00294 
00295 static void SetViewportPosition(Window *w, int x, int y)
00296 {
00297   ViewPort *vp = w->viewport;
00298   int old_left = vp->virtual_left;
00299   int old_top = vp->virtual_top;
00300   int i;
00301   int left, top, width, height;
00302 
00303   vp->virtual_left = x;
00304   vp->virtual_top = y;
00305 
00306   /* Viewport is bound to its left top corner, so it must be rounded down (UnScaleByZoomLower)
00307    * else glitch described in FS#1412 will happen (offset by 1 pixel with zoom level > NORMAL)
00308    */
00309   old_left = UnScaleByZoomLower(old_left, vp->zoom);
00310   old_top = UnScaleByZoomLower(old_top, vp->zoom);
00311   x = UnScaleByZoomLower(x, vp->zoom);
00312   y = UnScaleByZoomLower(y, vp->zoom);
00313 
00314   old_left -= x;
00315   old_top -= y;
00316 
00317   if (old_top == 0 && old_left == 0) return;
00318 
00319   _vp_move_offs.x = old_left;
00320   _vp_move_offs.y = old_top;
00321 
00322   left = vp->left;
00323   top = vp->top;
00324   width = vp->width;
00325   height = vp->height;
00326 
00327   if (left < 0) {
00328     width += left;
00329     left = 0;
00330   }
00331 
00332   i = left + width - _screen.width;
00333   if (i >= 0) width -= i;
00334 
00335   if (width > 0) {
00336     if (top < 0) {
00337       height += top;
00338       top = 0;
00339     }
00340 
00341     i = top + height - _screen.height;
00342     if (i >= 0) height -= i;
00343 
00344     if (height > 0) DoSetViewportPosition(w->z_front, left, top, width, height);
00345   }
00346 }
00347 
00356 ViewPort *IsPtInWindowViewport(const Window *w, int x, int y)
00357 {
00358   ViewPort *vp = w->viewport;
00359 
00360   if (vp != NULL &&
00361       IsInsideMM(x, vp->left, vp->left + vp->width) &&
00362       IsInsideMM(y, vp->top, vp->top + vp->height))
00363     return vp;
00364 
00365   return NULL;
00366 }
00367 
00375 static Point TranslateXYToTileCoord(const ViewPort *vp, int x, int y)
00376 {
00377   Point pt;
00378   int a, b;
00379   uint z;
00380 
00381   if ( (uint)(x -= vp->left) >= (uint)vp->width ||
00382         (uint)(y -= vp->top) >= (uint)vp->height) {
00383         Point pt = {-1, -1};
00384         return pt;
00385   }
00386 
00387   x = (ScaleByZoom(x, vp->zoom) + vp->virtual_left) >> 2;
00388   y = (ScaleByZoom(y, vp->zoom) + vp->virtual_top) >> 1;
00389 
00390   a = y - x;
00391   b = y + x;
00392 
00393   /* we need to move variables in to the valid range, as the
00394    * GetTileZoomCenterWindow() function can call here with invalid x and/or y,
00395    * when the user tries to zoom out along the sides of the map. */
00396   a = Clamp(a, ((uint)GetMaxTileHeight() + 1) / 4 * -(int)TILE_SIZE, (int)(MapMaxX() * TILE_SIZE) - 1);
00397   b = Clamp(b, ((uint)GetMaxTileHeight() + 1) / 4 * -(int)TILE_SIZE, (int)(MapMaxY() * TILE_SIZE) - 1);
00398 
00399   /* (a, b) is the X/Y-world coordinate that belongs to (x,y) if the landscape would be completely flat on height 0.
00400    * Now find the Z-world coordinate by fix point iteration.
00401    * This is a bit tricky because the tile height is non-continuous at foundations.
00402    * The clicked point should be approached from the back, otherwise there are regions that are not clickable.
00403    * (FOUNDATION_HALFTILE_LOWER on SLOPE_STEEP_S hides north halftile completely)
00404    * So give it a z-malus of 4 in the first iterations.
00405    */
00406   z = 0;
00407 
00408   int min_coord = _settings_game.construction.freeform_edges ? TILE_SIZE : 0;
00409 
00410   for (int i = 0; i < 5; i++) z = GetSlopeZ(Clamp(a + (int)max(z, 4u) - 4, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + (int)max(z, 4u) - 4, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
00411   for (uint malus = 3; malus > 0; malus--) z = GetSlopeZ(Clamp(a + (int)max(z, malus) - (int)malus, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + (int)max(z, malus) - (int)malus, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
00412   for (int i = 0; i < 5; i++) z = GetSlopeZ(Clamp(a + (int)z, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + (int)z, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
00413 
00414   pt.x = Clamp(a + (int)z, min_coord, MapMaxX() * TILE_SIZE - 1);
00415   pt.y = Clamp(b + (int)z, min_coord, MapMaxY() * TILE_SIZE - 1);
00416 
00417   return pt;
00418 }
00419 
00420 /* When used for zooming, check area below current coordinates (x,y)
00421  * and return the tile of the zoomed out/in position (zoom_x, zoom_y)
00422  * when you just want the tile, make x = zoom_x and y = zoom_y */
00423 static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
00424 {
00425   Window *w;
00426   ViewPort *vp;
00427   Point pt;
00428 
00429   if ( (w = FindWindowFromPt(x, y)) != NULL &&
00430        (vp = IsPtInWindowViewport(w, x, y)) != NULL)
00431         return TranslateXYToTileCoord(vp, zoom_x, zoom_y);
00432 
00433   pt.y = pt.x = -1;
00434   return pt;
00435 }
00436 
00437 Point GetTileBelowCursor()
00438 {
00439   return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, _cursor.pos.x, _cursor.pos.y);
00440 }
00441 
00442 
00443 Point GetTileZoomCenterWindow(bool in, Window * w)
00444 {
00445   int x, y;
00446   ViewPort *vp = w->viewport;
00447 
00448   if (in) {
00449     x = ((_cursor.pos.x - vp->left) >> 1) + (vp->width >> 2);
00450     y = ((_cursor.pos.y - vp->top) >> 1) + (vp->height >> 2);
00451   } else {
00452     x = vp->width - (_cursor.pos.x - vp->left);
00453     y = vp->height - (_cursor.pos.y - vp->top);
00454   }
00455   /* Get the tile below the cursor and center on the zoomed-out center */
00456   return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, x + vp->left, y + vp->top);
00457 }
00458 
00467 void HandleZoomMessage(Window *w, const ViewPort *vp, byte widget_zoom_in, byte widget_zoom_out)
00468 {
00469   w->SetWidgetDisabledState(widget_zoom_in, vp->zoom == ZOOM_LVL_MIN);
00470   w->SetWidgetDirty(widget_zoom_in);
00471 
00472   w->SetWidgetDisabledState(widget_zoom_out, vp->zoom == ZOOM_LVL_MAX);
00473   w->SetWidgetDirty(widget_zoom_out);
00474 }
00475 
00488 static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32 x, int32 y, int32 z, const SubSprite *sub = NULL, int extra_offs_x = 0, int extra_offs_y = 0)
00489 {
00490   assert((image & SPRITE_MASK) < MAX_SPRITES);
00491 
00492   TileSpriteToDraw *ts = _vd.tile_sprites_to_draw.Append();
00493   ts->image = image;
00494   ts->pal = pal;
00495   ts->sub = sub;
00496   Point pt = RemapCoords(x, y, z);
00497   ts->x = pt.x + extra_offs_x;
00498   ts->y = pt.y + extra_offs_y;
00499 }
00500 
00513 static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
00514 {
00515   assert(IsInsideMM(foundation_part, 0, FOUNDATION_PART_END));
00516   assert(_vd.foundation[foundation_part] != -1);
00517   Point offs = _vd.foundation_offset[foundation_part];
00518 
00519   /* Change the active ChildSprite list to the one of the foundation */
00520   int *old_child = _vd.last_child;
00521   _vd.last_child = _vd.last_foundation_child[foundation_part];
00522 
00523   AddChildSpriteScreen(image, pal, offs.x + extra_offs_x, offs.y + extra_offs_y, false, sub);
00524 
00525   /* Switch back to last ChildSprite list */
00526   _vd.last_child = old_child;
00527 }
00528 
00542 void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
00543 {
00544   /* Switch to first foundation part, if no foundation was drawn */
00545   if (_vd.foundation_part == FOUNDATION_PART_NONE) _vd.foundation_part = FOUNDATION_PART_NORMAL;
00546 
00547   if (_vd.foundation[_vd.foundation_part] != -1) {
00548     Point pt = RemapCoords(x, y, z);
00549     AddChildSpriteToFoundation(image, pal, sub, _vd.foundation_part, pt.x + extra_offs_x, pt.y + extra_offs_y);
00550   } else {
00551     AddTileSpriteToDraw(image, pal, _cur_ti->x + x, _cur_ti->y + y, _cur_ti->z + z, sub, extra_offs_x, extra_offs_y);
00552   }
00553 }
00554 
00565 void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
00566 {
00567   DrawGroundSpriteAt(image, pal, 0, 0, 0, sub, extra_offs_x, extra_offs_y);
00568 }
00569 
00577 void OffsetGroundSprite(int x, int y)
00578 {
00579   /* Switch to next foundation part */
00580   switch (_vd.foundation_part) {
00581     case FOUNDATION_PART_NONE:
00582       _vd.foundation_part = FOUNDATION_PART_NORMAL;
00583       break;
00584     case FOUNDATION_PART_NORMAL:
00585       _vd.foundation_part = FOUNDATION_PART_HALFTILE;
00586       break;
00587     default: NOT_REACHED();
00588   }
00589 
00590   /* _vd.last_child == NULL if foundation sprite was clipped by the viewport bounds */
00591   if (_vd.last_child != NULL) _vd.foundation[_vd.foundation_part] = _vd.parent_sprites_to_draw.Length() - 1;
00592 
00593   _vd.foundation_offset[_vd.foundation_part].x = x;
00594   _vd.foundation_offset[_vd.foundation_part].y = y;
00595   _vd.last_foundation_child[_vd.foundation_part] = _vd.last_child;
00596 }
00597 
00609 static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, int z, const SubSprite *sub)
00610 {
00611   Point pt = RemapCoords(x, y, z);
00612   const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
00613 
00614   if (pt.x + spr->x_offs >= _vd.dpi.left + _vd.dpi.width ||
00615       pt.x + spr->x_offs + spr->width <= _vd.dpi.left ||
00616       pt.y + spr->y_offs >= _vd.dpi.top + _vd.dpi.height ||
00617       pt.y + spr->y_offs + spr->height <= _vd.dpi.top)
00618     return;
00619 
00620   const ParentSpriteToDraw *pstd = _vd.parent_sprites_to_draw.End() - 1;
00621   AddChildSpriteScreen(image, pal, pt.x - pstd->left, pt.y - pstd->top, false, sub);
00622 }
00623 
00649 void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
00650 {
00651   int32 left, right, top, bottom;
00652 
00653   assert((image & SPRITE_MASK) < MAX_SPRITES);
00654 
00655   /* make the sprites transparent with the right palette */
00656   if (transparent) {
00657     SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
00658     pal = PALETTE_TO_TRANSPARENT;
00659   }
00660 
00661   if (_vd.combine_sprites == SPRITE_COMBINE_ACTIVE) {
00662     AddCombinedSprite(image, pal, x, y, z, sub);
00663     return;
00664   }
00665 
00666   _vd.last_child = NULL;
00667 
00668   Point pt = RemapCoords(x, y, z);
00669   int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
00670 
00671   /* Compute screen extents of sprite */
00672   if (image == SPR_EMPTY_BOUNDING_BOX) {
00673     left = tmp_left = RemapCoords(x + w          , y + bb_offset_y, z + bb_offset_z).x;
00674     right           = RemapCoords(x + bb_offset_x, y + h          , z + bb_offset_z).x + 1;
00675     top  = tmp_top  = RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz         ).y;
00676     bottom          = RemapCoords(x + w          , y + h          , z + bb_offset_z).y + 1;
00677   } else {
00678     const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
00679     left = tmp_left = (pt.x += spr->x_offs);
00680     right           = (pt.x +  spr->width );
00681     top  = tmp_top  = (pt.y += spr->y_offs);
00682     bottom          = (pt.y +  spr->height);
00683   }
00684 
00685   if (_draw_bounding_boxes && (image != SPR_EMPTY_BOUNDING_BOX)) {
00686     /* Compute maximal extents of sprite and its bounding box */
00687     left   = min(left  , RemapCoords(x + w          , y + bb_offset_y, z + bb_offset_z).x);
00688     right  = max(right , RemapCoords(x + bb_offset_x, y + h          , z + bb_offset_z).x + 1);
00689     top    = min(top   , RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz         ).y);
00690     bottom = max(bottom, RemapCoords(x + w          , y + h          , z + bb_offset_z).y + 1);
00691   }
00692 
00693   /* Do not add the sprite to the viewport, if it is outside */
00694   if (left   >= _vd.dpi.left + _vd.dpi.width ||
00695       right  <= _vd.dpi.left                 ||
00696       top    >= _vd.dpi.top + _vd.dpi.height ||
00697       bottom <= _vd.dpi.top) {
00698     return;
00699   }
00700 
00701   ParentSpriteToDraw *ps = _vd.parent_sprites_to_draw.Append();
00702   ps->x = tmp_x;
00703   ps->y = tmp_y;
00704 
00705   ps->left = tmp_left;
00706   ps->top  = tmp_top;
00707 
00708   ps->image = image;
00709   ps->pal = pal;
00710   ps->sub = sub;
00711   ps->xmin = x + bb_offset_x;
00712   ps->xmax = x + max(bb_offset_x, w) - 1;
00713 
00714   ps->ymin = y + bb_offset_y;
00715   ps->ymax = y + max(bb_offset_y, h) - 1;
00716 
00717   ps->zmin = z + bb_offset_z;
00718   ps->zmax = z + max(bb_offset_z, dz) - 1;
00719 
00720   ps->comparison_done = false;
00721   ps->first_child = -1;
00722 
00723   _vd.last_child = &ps->first_child;
00724 
00725   if (_vd.combine_sprites == SPRITE_COMBINE_PENDING) _vd.combine_sprites = SPRITE_COMBINE_ACTIVE;
00726 }
00727 
00746 void StartSpriteCombine()
00747 {
00748   assert(_vd.combine_sprites == SPRITE_COMBINE_NONE);
00749   _vd.combine_sprites = SPRITE_COMBINE_PENDING;
00750 }
00751 
00756 void EndSpriteCombine()
00757 {
00758   assert(_vd.combine_sprites != SPRITE_COMBINE_NONE);
00759   _vd.combine_sprites = SPRITE_COMBINE_NONE;
00760 }
00761 
00771 static bool IsInRangeInclusive(int begin, int end, int check)
00772 {
00773   if (begin > end) Swap(begin, end);
00774   return begin <= check && check <= end;
00775 }
00776 
00783 bool IsInsideRotatedRectangle(int x, int y)
00784 {
00785   int dist_a = (_thd.size.x + _thd.size.y);      // Rotated coordinate system for selected rectangle.
00786   int dist_b = (_thd.size.x - _thd.size.y);      // We don't have to divide by 2. It's all relative!
00787   int a = ((x - _thd.pos.x) + (y - _thd.pos.y)); // Rotated coordinate system for the point under scrutiny.
00788   int b = ((x - _thd.pos.x) - (y - _thd.pos.y));
00789 
00790   /* Check if a and b are between 0 and dist_a or dist_b respectively. */
00791   return IsInRangeInclusive(dist_a, 0, a) && IsInRangeInclusive(dist_b, 0, b);
00792 }
00793 
00804 void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub)
00805 {
00806   assert((image & SPRITE_MASK) < MAX_SPRITES);
00807 
00808   /* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
00809   if (_vd.last_child == NULL) return;
00810 
00811   /* make the sprites transparent with the right palette */
00812   if (transparent) {
00813     SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
00814     pal = PALETTE_TO_TRANSPARENT;
00815   }
00816 
00817   *_vd.last_child = _vd.child_screen_sprites_to_draw.Length();
00818 
00819   ChildScreenSpriteToDraw *cs = _vd.child_screen_sprites_to_draw.Append();
00820   cs->image = image;
00821   cs->pal = pal;
00822   cs->sub = sub;
00823   cs->x = x;
00824   cs->y = y;
00825   cs->next = -1;
00826 
00827   /* Append the sprite to the active ChildSprite list.
00828    * If the active ParentSprite is a foundation, update last_foundation_child as well.
00829    * Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
00830   if (_vd.last_foundation_child[0] == _vd.last_child) _vd.last_foundation_child[0] = &cs->next;
00831   if (_vd.last_foundation_child[1] == _vd.last_child) _vd.last_foundation_child[1] = &cs->next;
00832   _vd.last_child = &cs->next;
00833 }
00834 
00835 static void AddStringToDraw(int x, int y, StringID string, uint64 params_1, uint64 params_2, Colours colour, uint16 width)
00836 {
00837   assert(width != 0);
00838   StringSpriteToDraw *ss = _vd.string_sprites_to_draw.Append();
00839   ss->string = string;
00840   ss->x = x;
00841   ss->y = y;
00842   ss->params[0] = params_1;
00843   ss->params[1] = params_2;
00844   ss->width = width;
00845   ss->colour = colour;
00846 }
00847 
00848 
00860 static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part)
00861 {
00862   /* FIXME: This is not totally valid for some autorail highlights that extend over the edges of the tile. */
00863   if (_vd.foundation[foundation_part] == -1) {
00864     /* draw on real ground */
00865     AddTileSpriteToDraw(image, pal, ti->x, ti->y, ti->z + z_offset);
00866   } else {
00867     /* draw on top of foundation */
00868     AddChildSpriteToFoundation(image, pal, NULL, foundation_part, 0, -z_offset);
00869   }
00870 }
00871 
00878 static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
00879 {
00880   if (!IsValidTile(ti->tile)) return;
00881 
00882   SpriteID sel;
00883   if (IsHalftileSlope(ti->tileh)) {
00884     Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
00885     SpriteID sel2 = SPR_HALFTILE_SELECTION_FLAT + halftile_corner;
00886     DrawSelectionSprite(sel2, pal, ti, 7 + TILE_HEIGHT, FOUNDATION_PART_HALFTILE);
00887 
00888     Corner opposite_corner = OppositeCorner(halftile_corner);
00889     if (IsSteepSlope(ti->tileh)) {
00890       sel = SPR_HALFTILE_SELECTION_DOWN;
00891     } else {
00892       sel = ((ti->tileh & SlopeWithOneCornerRaised(opposite_corner)) != 0 ? SPR_HALFTILE_SELECTION_UP : SPR_HALFTILE_SELECTION_FLAT);
00893     }
00894     sel += opposite_corner;
00895   } else {
00896     sel = SPR_SELECT_TILE + SlopeToSpriteOffset(ti->tileh);
00897   }
00898   DrawSelectionSprite(sel, pal, ti, 7, FOUNDATION_PART_NORMAL);
00899 }
00900 
00901 static void DrawPreviewSprite(SpriteID image, SpriteID pal, uint x, uint y, uint z)
00902 {
00903   //DrawGroundSpriteAt(image, x, y, z + 7);
00904   AddSortableSpriteToDraw(image, pal, x, y, 0x10, 0x10, 1, z + 7);
00905 }
00906 
00907 static bool IsPartOfAutoLine(int px, int py)
00908 {
00909   px -= _thd.selstart.x;
00910   py -= _thd.selstart.y;
00911 
00912   if ((_thd.drawstyle & HT_DRAG_MASK) != HT_LINE) return false;
00913 
00914   switch (_thd.drawstyle & HT_DIR_MASK) {
00915     case HT_DIR_X:  return py == 0; // x direction
00916     case HT_DIR_Y:  return px == 0; // y direction
00917     case HT_DIR_HU: return px == -py || px == -py - 16; // horizontal upper
00918     case HT_DIR_HL: return px == -py || px == -py + 16; // horizontal lower
00919     case HT_DIR_VL: return px == py || px == py + 16; // vertical left
00920     case HT_DIR_VR: return px == py || px == py - 16; // vertical right
00921     default:
00922       NOT_REACHED();
00923   }
00924 }
00925 
00926 /* [direction][side] */
00927 static const HighLightStyle _autorail_type[6][2] = {
00928   { HT_DIR_X,  HT_DIR_X },
00929   { HT_DIR_Y,  HT_DIR_Y },
00930   { HT_DIR_HU, HT_DIR_HL },
00931   { HT_DIR_HL, HT_DIR_HU },
00932   { HT_DIR_VL, HT_DIR_VR },
00933   { HT_DIR_VR, HT_DIR_VL }
00934 };
00935 
00936 #include "table/autorail.h"
00937 
00938 /*
00939 static uint GetTileHFromCopyBuffer(TileIndex index, uint32 baseh, uint32* h)
00940 {
00941   return GetTileh((uint)_copy_heightmap[index] + baseh, (uint)_copy_heightmap[index+1] + baseh, (uint)_copy_heightmap[index + _copy_width] + baseh, (uint)_copy_heightmap[index + _copy_width + 1] + baseh, h);
00942 }
00943 */
00944 
00945 static void DrawPreviewTile(const TileInfo *ti)
00946 {
00947   uint32 image;
00948   //We have to get the index within our _copy_paste.m_rail[] structure
00949   uint32 tile_x = ti->x / TILE_SIZE;
00950   uint32 tile_y = ti->y / TILE_SIZE;
00951   uint32 pos_x = _thd.pos.x / TILE_SIZE;
00952   uint32 pos_y = _thd.pos.y / TILE_SIZE;
00953   uint32 bindex = (tile_x - pos_x) + ((_copy_paste.GetWidth() - 1) * (tile_y - pos_y));
00954   //uint32 baseh = TileHeight(TileXY(pos_x, pos_y));
00955   //uint32 tindex = (tile_x - pos_x) + ((_copy_width) * (tile_y - pos_y));
00956   //uint32 minh;
00957   //uint32 tileh = GetTileHFromCopyBuffer(tindex, baseh, &minh);
00958   
00959   if (((tile_x - pos_x) == 0) || ((tile_x - pos_x) == (_copy_paste.GetWidth() - 2)) || ((tile_y - pos_y) == 0) || ((tile_y - pos_y) == (_copy_paste.GetHeight() - 2))) {
00960     //Highlight BorderTiles
00961     image = SPR_SELECT_TILE + SlopeToSpriteOffset(ti->tileh);
00962     DrawPreviewSprite(image, PAL_NONE, ti->x, ti->y, ti->z);
00963   }
00964   
00965   image = SPR_AUTORAIL_BASE;
00966   TrackBits tracktodraw = _copy_paste.GetCPTrackBits(bindex);
00967   for (Track t = TRACK_BEGIN; t < TRACK_END; t++) {
00968     if (tracktodraw & TrackToTrackBits(t)) DrawPreviewSprite(image + _AutorailTilehSprite[SLOPE_FLAT][t], PAL_NONE, ti->x, ti->y, ti->z);
00969   }
00970   
00971   /*
00972   if ((_copy_rail[bindex] & (1U << TRACK_X))>0) DrawPreviewSprite(image, ti->x, ti->y, minh);
00973   if ((_copy_rail[bindex] & (1U << TRACK_Y))>0) DrawPreviewSprite(image + 8, ti->x, ti->y, minh);
00974   if ((_copy_rail[bindex] & (1U << TRACK_UPPER))>0) DrawPreviewSprite(image + 16, ti->x, ti->y, minh);
00975   if ((_copy_rail[bindex] & (1U << TRACK_LOWER))>0) DrawPreviewSprite(image + 25, ti->x, ti->y, minh);
00976   if ((_copy_rail[bindex] & (1U << TRACK_LEFT))>0) DrawPreviewSprite(image + 34, ti->x, ti->y, minh);
00977   if ((_copy_rail[bindex] & (1U << TRACK_RIGHT))>0) DrawPreviewSprite(image + 42, ti->x, ti->y, minh);
00978   
00979   */
00980 }
00981 
00988 static void DrawAutorailSelection(const TileInfo *ti, uint autorail_type)
00989 {
00990   SpriteID image;
00991   PaletteID pal;
00992   int offset;
00993 
00994   FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
00995   Slope autorail_tileh = RemoveHalftileSlope(ti->tileh);
00996   if (IsHalftileSlope(ti->tileh)) {
00997     static const uint _lower_rail[4] = { 5U, 2U, 4U, 3U };
00998     Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
00999     if (autorail_type != _lower_rail[halftile_corner]) {
01000       foundation_part = FOUNDATION_PART_HALFTILE;
01001       /* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
01002       autorail_tileh = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
01003     }
01004   }
01005 
01006   offset = _AutorailTilehSprite[autorail_tileh][autorail_type];
01007   if (offset >= 0) {
01008     image = SPR_AUTORAIL_BASE + offset;
01009     pal = PAL_NONE;
01010   } else {
01011     image = SPR_AUTORAIL_BASE - offset;
01012     pal = PALETTE_SEL_TILE_RED;
01013   }
01014 
01015   DrawSelectionSprite(image, _thd.make_square_red ? PALETTE_SEL_TILE_RED : pal, ti, 7, foundation_part);
01016 }
01017 
01022 static void DrawTileSelection(const TileInfo *ti)
01023 {
01024   /* Draw a red error square? */
01025   bool is_redsq = _thd.redsq == ti->tile;
01026   if (is_redsq) DrawTileSelectionRect(ti, PALETTE_TILE_RED_PULSATING);
01027 
01028   /* No tile selection active? */
01029   if ((_thd.drawstyle & HT_DRAG_MASK) == HT_NONE) return;
01030 
01031   if (_thd.diagonal) { // We're drawing a 45 degrees rotated (diagonal) rectangle
01032     if (IsInsideRotatedRectangle((int)ti->x, (int)ti->y)) goto draw_inner;
01033     return;
01034   }
01035 
01036   /* Inside the inner area? */
01037   if (IsInsideBS(ti->x, _thd.pos.x, _thd.size.x) &&
01038       IsInsideBS(ti->y, _thd.pos.y, _thd.size.y)) {
01039 draw_inner:
01040     if (_thd.drawstyle & HT_RECT) {
01041       if (!is_redsq) DrawTileSelectionRect(ti, _thd.make_square_red ? PALETTE_SEL_TILE_RED : PAL_NONE);
01042     } else if (_thd.drawstyle & HT_POINT) {
01043       /* Figure out the Z coordinate for the single dot. */
01044       int z = 0;
01045       FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
01046       if (ti->tileh & SLOPE_N) {
01047         z += TILE_HEIGHT;
01048         if (RemoveHalftileSlope(ti->tileh) == SLOPE_STEEP_N) z += TILE_HEIGHT;
01049       }
01050       if (IsHalftileSlope(ti->tileh)) {
01051         Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
01052         if ((halftile_corner == CORNER_W) || (halftile_corner == CORNER_E)) z += TILE_HEIGHT;
01053         if (halftile_corner != CORNER_S) {
01054           foundation_part = FOUNDATION_PART_HALFTILE;
01055           if (IsSteepSlope(ti->tileh)) z -= TILE_HEIGHT;
01056         }
01057       }
01058       DrawSelectionSprite(_cur_dpi->zoom <= ZOOM_LVL_DETAIL ? SPR_DOT : SPR_DOT_SMALL, PAL_NONE, ti, z, foundation_part);
01059     } else if (_thd.drawstyle & HT_RAIL) {
01060       /* autorail highlight piece under cursor */
01061       HighLightStyle type = _thd.drawstyle & HT_DIR_MASK;
01062       assert(type < HT_DIR_END);
01063       DrawAutorailSelection(ti, _autorail_type[type][0]);
01064     } else if (_thd.drawstyle & HT_PREVIEW) {
01065       DrawPreviewTile(ti);
01066     } else if (IsPartOfAutoLine(ti->x, ti->y)) {
01067       /* autorail highlighting long line */
01068       HighLightStyle dir = _thd.drawstyle & HT_DIR_MASK;
01069       uint side;
01070 
01071       if (dir == HT_DIR_X || dir == HT_DIR_Y) {
01072         side = 0;
01073       } else {
01074         TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
01075         side = Delta(Delta(TileX(start), TileX(ti->tile)), Delta(TileY(start), TileY(ti->tile)));
01076       }
01077 
01078       DrawAutorailSelection(ti, _autorail_type[dir][side]);
01079     }
01080     return;
01081   }
01082 
01083   /* Check if it's inside the outer area? */
01084   if (!is_redsq && _thd.outersize.x > 0 &&
01085       IsInsideBS(ti->x, _thd.pos.x + _thd.offs.x, _thd.size.x + _thd.outersize.x) &&
01086       IsInsideBS(ti->y, _thd.pos.y + _thd.offs.y, _thd.size.y + _thd.outersize.y)) {
01087     /* Draw a blue rect. */
01088     DrawTileSelectionRect(ti, PALETTE_SEL_TILE_BLUE);
01089     return;
01090   }
01091 }
01092 
01101 static inline Point GetTileCoordFromScreenCoord(int x, int y)
01102 {
01103   /* First convert from the screen coordinate system (where the width of tiles
01104    * is twice their height) to the tile coordinate system. That means, turn
01105    * around by 45 degrees and make the tiles quadratic. */
01106   Point tile_coord = InverseRemapCoords(x, y);
01107 
01108   /* Scale from a 16x16-grid to a 1x1-grid as returned by TileX/TileY. */
01109   tile_coord.x /= (int)TILE_SIZE;
01110   tile_coord.y /= (int)TILE_SIZE;
01111 
01112   return tile_coord;
01113 }
01114 
01131 static Point GetMinTileCoordsIgnoringHeight(int x, int y)
01132 {
01133   Point tile_coord = GetTileCoordFromScreenCoord(x, y);
01134 
01135   /* Expand area to be painted in order to avoid situations
01136    * where south or east of the to be painted point in dpi are tiles
01137    * which will not be painted. */
01138   tile_coord.y--;
01139 
01140   return tile_coord;
01141 }
01142 
01159 static Point GetMaxTileCoordsIgnoringHeight(int x, int y)
01160 {
01161   Point tile_coord = GetTileCoordFromScreenCoord(x, y);
01162 
01163   /* Expand area to be painted to southeast in order to avoid situations
01164    * where north or east of the given to be painted point in dpi are
01165    * tiles which will not be repainted. */
01166   tile_coord.y++;
01167 
01168   return tile_coord;
01169 }
01170 
01180 static int GetTileColumnFromTileCoord(Point tile_coord)
01181 {
01182   return tile_coord.y - tile_coord.x;
01183 }
01184 
01191 static int GetViewportY(Point tile)
01192 {
01193   return tile.y * TILE_SIZE + tile.x * TILE_SIZE - GetTileMaxZOutsideMap(tile.x, tile.y);
01194 }
01195 
01202 static Point GetNorthernEndOfColumn(Point tile)
01203 {
01204   Point distance_to_end;
01205   distance_to_end.x = (int)MapMaxX() - tile.x;
01206   distance_to_end.y = (int)MapMaxY() - tile.y;
01207   Point northern_end;
01208 
01209   if (tile.x < tile.y) {
01210     northern_end.x = 0;
01211     northern_end.y = tile.y - tile.x;
01212   } else {
01213     northern_end.x = tile.x - tile.y;
01214     northern_end.y = 0;
01215   }
01216 
01217   return northern_end;
01218 }
01219 
01226 static Point GetSouthernEndOfColumn(Point tile)
01227 {
01228   Point distance_to_end;
01229   distance_to_end.x = (int)MapMaxX() - tile.x;
01230   distance_to_end.y = (int)MapMaxY() - tile.y;
01231   Point southern_end;
01232 
01233   if (distance_to_end.x < distance_to_end.y) {
01234     southern_end.x = tile.x + distance_to_end.x;
01235     southern_end.y = tile.y + distance_to_end.x;
01236   } else {
01237     southern_end.x = tile.x + distance_to_end.y;
01238     southern_end.y = tile.y + distance_to_end.y;
01239   }
01240 
01241   return southern_end;
01242 }
01243 
01251 static Point GetMiddleTile(Point upper_tile, Point lower_tile) {
01252   /* If upper_tile is lower than lower_tile swap tiles.
01253    * Since we are only interested in the middle tile here, it is safe to do so. */
01254   if (upper_tile.x <= lower_tile.x) Swap(upper_tile.x, lower_tile.x);
01255   if (upper_tile.y <= lower_tile.y) Swap(upper_tile.y, lower_tile.y);
01256   
01257   Point middle_tile;
01258 
01259   middle_tile.x = upper_tile.x + (lower_tile.x - upper_tile.x) / 2;
01260   middle_tile.y = upper_tile.y + (lower_tile.y - upper_tile.y) / 2;
01261   return middle_tile;
01262 }
01263 
01291 int GetRowAtTile(int viewport_y, Point tile)
01292 {
01293   Point northern_tile = GetNorthernEndOfColumn(tile);
01294   Point southern_tile = GetSouthernEndOfColumn(tile);
01295 
01296   int northern_tile_viewport_y = GetViewportY(northern_tile);
01297   int southern_tile_viewport_y = GetViewportY(southern_tile);
01298 
01299   if (northern_tile_viewport_y >= viewport_y) {
01300     /* We are north of the map, search tile by tile with direction north. */
01301     while (northern_tile_viewport_y >= viewport_y) {
01302       northern_tile.x--;
01303       northern_tile.y--;
01304       northern_tile_viewport_y = GetViewportY(northern_tile);
01305     }
01306 
01307     return northern_tile.x + northern_tile.y;
01308   } else if (southern_tile_viewport_y <= viewport_y) {
01309     /* We are south of the map, search tile by tile with direction south. */
01310     while (southern_tile_viewport_y <= viewport_y) {
01311       southern_tile.x++;
01312       southern_tile.y++;
01313       southern_tile_viewport_y = GetViewportY(southern_tile);
01314     }
01315 
01316     DEBUG(driver, 9, "==> We are south of the map => Returning row for (%i,%i)",
01317         southern_tile.x, southern_tile.y);
01318 
01319     return southern_tile.x + southern_tile.y;
01320   } else {
01321       /* We are inside the map. */
01322 
01323       /* Invariant in the code below: The searched tile shown at viewport_y
01324      * always is between upper_tile and lower_tile. */
01325     Point upper_tile = tile;
01326     Point lower_tile = GetSouthernEndOfColumn(upper_tile);
01327     int middle_bound;
01328 
01329     DEBUG(driver, 9, "==> GetRowAtTile for vp_y = %i, (upper_)tile (%i,%i), lower_tile (%i,%i)",
01330         viewport_y, upper_tile.x, upper_tile.y, lower_tile.x, lower_tile.y);
01331 
01332     do {
01333       Point middle_tile = GetMiddleTile(upper_tile, lower_tile);
01334       middle_bound = GetViewportY(middle_tile);
01335 
01336       DEBUG(driver, 9, "====> upper: (%i,%i), middle (%i,%i), lower (%i,%i); m_bound = %i",
01337           upper_tile.x, upper_tile.y, middle_tile.x, middle_tile.y,
01338           lower_tile.x, lower_tile.y, middle_bound);
01339 
01340       if (middle_bound >= viewport_y) {
01341         /* The tile shown at viewport_y is somewhere in the upper half of
01342          * the currently observed section. */
01343         lower_tile = middle_tile;
01344       } else {
01345         /* The tile shown at viewport_y is somewhere in the lower half of
01346          * the currently observed section. */
01347         upper_tile = middle_tile;
01348       }
01349     }
01350     while (lower_tile.y - upper_tile.y > 1);
01351 
01352     /* Now our interval has length 1, so it only contains two tiles, and we take
01353      * the upper one, calculating and returning its row. */
01354     return upper_tile.x + upper_tile.y;
01355   }
01356 }
01357 
01372 static Point GetBottomTileOfColumn(Point upper_tile, Point lower_right_tile)
01373 {
01374   int upper_row = upper_tile.x + upper_tile.y;
01375   int lower_row = lower_right_tile.x + lower_right_tile.y;
01376 
01377   assert(upper_row <= lower_row);
01378 
01379   int number_of_rows = lower_row - upper_row;
01380 
01381   if (number_of_rows % 2 != 0) {
01382     /* Avoid 0.5 being rounded down to zero; painting too much is better than
01383      * painting to less. */
01384     number_of_rows++;
01385   }
01386 
01387   Point bottom_tile;
01388   bottom_tile.x = upper_tile.x + number_of_rows / 2;
01389   bottom_tile.y = upper_tile.y + number_of_rows / 2;
01390 
01391   int bottom_row = bottom_tile.x + bottom_tile.y;
01392 
01393   assert(bottom_row >= lower_row);
01394 
01395   return bottom_tile;
01396 }
01397 
01398 static void ViewportAddLandscape()
01399 {
01400   assert(_vd.dpi.top <= _vd.dpi.top + _vd.dpi.height);
01401   assert(_vd.dpi.left <= _vd.dpi.left + _vd.dpi.width);
01402 
01403   /* The upper and lower edge of the viewport part to paint. Add some number
01404    * of pixels to the lower end in order to ensure that we also take tiles
01405    * south of the given area, but with high buildings intersecting the area.
01406    * Subtract some pixels from the upper end in order to avoid glitches at the
01407    * upper end of the top be painted area. */
01408   int viewport_top = _vd.dpi.top - 16;
01409   int viewport_bottom = _vd.dpi.top + _vd.dpi.height + 116;
01410 
01411   DEBUG(driver, 9, "viewport: x = %i, y = %i, w = %i, h = %i",
01412       _vd.dpi.left, _vd.dpi.top, _vd.dpi.width, _vd.dpi.height);
01413 
01414   DEBUG(driver, 9, "viewport_top = %i, viewport_bottom = %i",
01415       viewport_top, viewport_bottom);
01416 
01417   /* First get the position of the tile at the upper left / lower right edge,
01418    * for now ignoring the height. (i.e. assuming height zero.) */
01419   Point upper_left_tile = GetMinTileCoordsIgnoringHeight(_vd.dpi.left, viewport_top);
01420   Point lower_right_tile = GetMaxTileCoordsIgnoringHeight(_vd.dpi.left + _vd.dpi.width, viewport_bottom);
01421 
01422   DEBUG(driver, 9, "upper_left_tile = (%i,%i); lower_right_tile = (%i,%i)",
01423       upper_left_tile.x, upper_left_tile.y, lower_right_tile.x, lower_right_tile.y);
01424 
01425   /* Calculate the bounding columns. We won't need to draw anything
01426    * left / right of them. */
01427   int left_column = GetTileColumnFromTileCoord(upper_left_tile);
01428   /* Correction to avoid glitches when approaching the left edge of the map. */
01429   left_column--;
01430   int right_column = GetTileColumnFromTileCoord(lower_right_tile);
01431   right_column++;
01432 
01433   DEBUG(driver, 9, "left_column = %i, right_column = %i",
01434       left_column, right_column);
01435 
01436   /* For each column, calculate the top and the bottom row. These are the
01437    * bounding rows for that specific column. */
01438   int *top_row = AllocaM(int, right_column - left_column + 1); // Pre-allocate memory for visual studio/express to be able to compile.
01439   int *bottom_row = AllocaM(int, right_column - left_column + 1); // Pre-allocate memory for visual studio/express to be able to compile.
01440   int min_top_row = MapMaxX() + MapMaxY();
01441   int max_bottom_row = 0;
01442   Point top_tile_of_column = upper_left_tile;
01443 
01444   /* And now for each column, determine the top and the bottom row we must paint. */
01445   bool south_east_direction = false;
01446   for (int x = left_column; x <= right_column; x++) {
01447     Point bottom_tile_of_column = GetBottomTileOfColumn(top_tile_of_column, lower_right_tile);
01448 
01449     DEBUG(driver, 9, "Inspecting column %i; top_tile=(%i,%i); bottom_tile=(%i, %i)",
01450         x, top_tile_of_column.x, top_tile_of_column.y,
01451         bottom_tile_of_column.x, bottom_tile_of_column.y);
01452 
01453     /* And then actually find out the top and the bottom row. Note that
01454      * top_tile_of_column and bottom_tile_of_column may be outside the map here.
01455      * This possibility is needed, otherwise we couldn't paint the black area
01456      * outside the map (and in particular the edge of map) properly.
01457      * Subtract three / add one to avoid glitches. */
01458     top_row[x - left_column] = GetRowAtTile(viewport_top, top_tile_of_column);
01459 
01460     DEBUG(driver, 9, "GetRowAtTile for viewport_top = %i and top_tile_of_column = (%i,%i) is %i",
01461         viewport_top, top_tile_of_column.x, top_tile_of_column.y, top_row[x - left_column]);
01462 
01463     top_row[x - left_column] -= 3;
01464     bottom_row[x - left_column] = GetRowAtTile(viewport_bottom, bottom_tile_of_column);
01465     bottom_row[x - left_column]++;
01466 
01467     /* We never paint things in rows < min_top_row or > max_bottom_row. */
01468     min_top_row = min(min_top_row, top_row[x - left_column]);
01469     max_bottom_row = max(max_bottom_row, bottom_row[x - left_column]);
01470 
01471     /* Go to next column in the east. */
01472     if (south_east_direction) {
01473       top_tile_of_column.y++;
01474     } else {
01475       top_tile_of_column.x--;
01476     }
01477 
01478     /* Switch between directions southeast and northeast. */
01479     south_east_direction = !south_east_direction;
01480   }
01481 
01482   for (int n = 0; n < right_column - left_column + 1; n++) {
01483 
01484     DEBUG(driver, 9, "==> top/bottom of column %i is %i .. %i",
01485         left_column + n, top_row[n], bottom_row[n]);
01486   }
01487 
01488   for (int row = min_top_row; row <= max_bottom_row; row++) {
01489     for (int column = left_column; column <= right_column; column++) {
01490       /* For each column, we only paint the interval top_row .. bottom_row.
01491        * Due to the division by two below, even and odd values of row + column map to
01492        * the same (x,y) combinations. Thus, we only paint one of them. */
01493       if (((row + column) % 2 == 0)
01494         && (top_row[column - left_column] <= row)
01495         && (row <= bottom_row[column - left_column])) {
01496 
01497         TileType tile_type;
01498         TileInfo tile_info;
01499         /* Copied from the old code, I know that the treatment of that
01500          * global variable is not very nice - By modifying tile_info
01501          * below, we also modify _cur_ti! */
01502         _cur_ti = &tile_info;
01503 
01504         /* column = y - x; row = x + y; now solve the equation system
01505          * for x and y. */
01506         int x = (row - column) / 2;
01507         int y = (row + column) / 2;
01508         tile_info.x = x;
01509         tile_info.y = y;
01510 
01511         /* For some strange reason, those fields inside tile_info are uints. However,
01512          * in the old code their copies in an int variable where compared against zero. */
01513         if (0 < x && x < (int)MapMaxX()
01514           && 0 < y && y < (int)MapMaxY()) {
01515           /* We are inside the map => paint landscape. */
01516           tile_info.tile = TileXY(tile_info.x, tile_info.y);
01517           tile_info.tileh = GetTileSlope(tile_info.tile, &tile_info.z);
01518           tile_type = GetTileType(tile_info.tile);
01519         } else {
01520           /* We are outside the map => paint black. */
01521           tile_info.tile = 0;
01522           tile_info.tileh = GetTileSlopeOutsideMap(tile_info.x, tile_info.y, &tile_info.z);
01523           tile_type = MP_VOID;
01524         }
01525 
01526         /* Scale to 16x16 tiles, needed for the drawing procedures called below. */
01527         tile_info.x *= TILE_SIZE;
01528         tile_info.y *= TILE_SIZE;
01529 
01530         _vd.foundation_part = FOUNDATION_PART_NONE;
01531         _vd.foundation[0] = -1;
01532         _vd.foundation[1] = -1;
01533         _vd.last_foundation_child[0] = NULL;
01534         _vd.last_foundation_child[1] = NULL;
01535 
01536         _tile_type_procs[tile_type]->draw_tile_proc(&tile_info);
01537         DrawTileSelection(&tile_info);
01538       }
01539     }
01540   }
01541 }
01542 
01553 void ViewportAddString(const DrawPixelInfo *dpi, ZoomLevel small_from, const ViewportSign *sign, StringID string_normal, StringID string_small, StringID string_small_shadow, uint64 params_1, uint64 params_2, Colours colour)
01554 {
01555   bool small = dpi->zoom >= small_from;
01556 
01557   int left   = dpi->left;
01558   int top    = dpi->top;
01559   int right  = left + dpi->width;
01560   int bottom = top + dpi->height;
01561 
01562   int sign_height     = ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM, dpi->zoom);
01563   int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, dpi->zoom);
01564 
01565   if (bottom < sign->top ||
01566       top   > sign->top + sign_height ||
01567       right < sign->center - sign_half_width ||
01568       left  > sign->center + sign_half_width) {
01569     return;
01570   }
01571 
01572   if (!small) {
01573     AddStringToDraw(sign->center - sign_half_width, sign->top, string_normal, params_1, params_2, colour, sign->width_normal);
01574   } else {
01575     int shadow_offset = 0;
01576     if (string_small_shadow != STR_NULL) {
01577       shadow_offset = 4;
01578       AddStringToDraw(sign->center - sign_half_width + shadow_offset, sign->top, string_small_shadow, params_1, params_2, INVALID_COLOUR, sign->width_small);
01579     }
01580     AddStringToDraw(sign->center - sign_half_width, sign->top - shadow_offset, string_small, params_1, params_2,
01581         colour, sign->width_small | 0x8000);
01582   }
01583 }
01584 
01585 static void ViewportAddTownNames(DrawPixelInfo *dpi)
01586 {
01587   if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES) || _game_mode == GM_MENU) return;
01588 
01589   const Town *t;
01590   FOR_ALL_TOWNS(t) {
01591     ViewportAddString(dpi, ZOOM_LVL_OUT_4X, &t->sign,
01592         t->Label(), t->SmallLabel(), STR_VIEWPORT_TOWN_TINY_BLACK,
01593         t->index, t->population);
01594   }
01595 }
01596 
01597 
01598 static void ViewportAddStationNames(DrawPixelInfo *dpi)
01599 {
01600   if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || _game_mode == GM_MENU) return;
01601 
01602   const BaseStation *st;
01603   FOR_ALL_BASE_STATIONS(st) {
01604     /* Check whether the base station is a station or a waypoint */
01605     bool is_station = Station::IsExpected(st);
01606 
01607     /* Don't draw if the display options are disabled */
01608     if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
01609 
01610     ViewportAddString(dpi, ZOOM_LVL_OUT_4X, &st->sign,
01611         is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT,
01612         (is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT) + 1, STR_NULL,
01613         st->index, st->facilities, (st->owner == OWNER_NONE || !st->IsInUse()) ? COLOUR_GREY : _company_colours[st->owner]);
01614   }
01615 }
01616 
01617 
01618 static void ViewportAddSigns(DrawPixelInfo *dpi)
01619 {
01620   /* Signs are turned off or are invisible */
01621   if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS)) return;
01622 
01623   const Sign *si;
01624   FOR_ALL_SIGNS(si) {
01625     ViewportAddString(dpi, ZOOM_LVL_OUT_4X, &si->sign,
01626         STR_WHITE_SIGN,
01627         IsTransparencySet(TO_SIGNS) ? STR_VIEWPORT_SIGN_SMALL_WHITE : STR_VIEWPORT_SIGN_SMALL_BLACK, STR_NULL,
01628         si->index, 0, (si->owner == OWNER_NONE) ? COLOUR_GREY : _company_colours[si->owner]);
01629   }
01630 }
01631 
01638 void ViewportSign::UpdatePosition(int center, int top, StringID str)
01639 {
01640   if (this->width_normal != 0) this->MarkDirty();
01641 
01642   this->top = top;
01643 
01644   char buffer[DRAW_STRING_BUFFER];
01645 
01646   GetString(buffer, str, lastof(buffer));
01647   this->width_normal = VPSM_LEFT + Align(GetStringBoundingBox(buffer).width, 2) + VPSM_RIGHT;
01648   this->center = center;
01649 
01650   /* zoomed out version */
01651   this->width_small = VPSM_LEFT + Align(GetStringBoundingBox(buffer, FS_SMALL).width, 2) + VPSM_RIGHT;
01652 
01653   this->MarkDirty();
01654 }
01655 
01661 void ViewportSign::MarkDirty() const
01662 {
01663   /* We use ZOOM_LVL_MAX here, as every viewport can have another zoom,
01664    *  and there is no way for us to know which is the biggest. So make the
01665    *  biggest area dirty, and we are safe for sure.
01666    * We also add 1 to make sure the whole thing is redrawn. */
01667   MarkAllViewportsDirty(
01668     this->center - ScaleByZoom(this->width_normal / 2 + 1, ZOOM_LVL_MAX),
01669     this->top    - ScaleByZoom(1, ZOOM_LVL_MAX),
01670     this->center + ScaleByZoom(this->width_normal / 2 + 1, ZOOM_LVL_MAX),
01671     this->top    + ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM + 1, ZOOM_LVL_MAX));
01672 }
01673 
01674 static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
01675 {
01676   const TileSpriteToDraw *tsend = tstdv->End();
01677   for (const TileSpriteToDraw *ts = tstdv->Begin(); ts != tsend; ++ts) {
01678     DrawSprite(ts->image, ts->pal, ts->x, ts->y, ts->sub);
01679   }
01680 }
01681 
01683 static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
01684 {
01685   ParentSpriteToDraw **psdvend = psdv->End();
01686   ParentSpriteToDraw **psd = psdv->Begin();
01687   while (psd != psdvend) {
01688     ParentSpriteToDraw *ps = *psd;
01689 
01690     if (ps->comparison_done) {
01691       psd++;
01692       continue;
01693     }
01694 
01695     ps->comparison_done = true;
01696 
01697     for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) {
01698       ParentSpriteToDraw *ps2 = *psd2;
01699 
01700       if (ps2->comparison_done) continue;
01701 
01702       /* Decide which comparator to use, based on whether the bounding
01703        * boxes overlap
01704        */
01705       if (ps->xmax >= ps2->xmin && ps->xmin <= ps2->xmax && // overlap in X?
01706           ps->ymax >= ps2->ymin && ps->ymin <= ps2->ymax && // overlap in Y?
01707           ps->zmax >= ps2->zmin && ps->zmin <= ps2->zmax) { // overlap in Z?
01708         /* Use X+Y+Z as the sorting order, so sprites closer to the bottom of
01709          * the screen and with higher Z elevation, are drawn in front.
01710          * Here X,Y,Z are the coordinates of the "center of mass" of the sprite,
01711          * i.e. X=(left+right)/2, etc.
01712          * However, since we only care about order, don't actually divide / 2
01713          */
01714         if (ps->xmin + ps->xmax + ps->ymin + ps->ymax + ps->zmin + ps->zmax <=
01715             ps2->xmin + ps2->xmax + ps2->ymin + ps2->ymax + ps2->zmin + ps2->zmax) {
01716           continue;
01717         }
01718       } else {
01719         /* We only change the order, if it is definite.
01720          * I.e. every single order of X, Y, Z says ps2 is behind ps or they overlap.
01721          * That is: If one partial order says ps behind ps2, do not change the order.
01722          */
01723         if (ps->xmax < ps2->xmin ||
01724             ps->ymax < ps2->ymin ||
01725             ps->zmax < ps2->zmin) {
01726           continue;
01727         }
01728       }
01729 
01730       /* Move ps2 in front of ps */
01731       ParentSpriteToDraw *temp = ps2;
01732       for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) {
01733         *psd3 = *(psd3 - 1);
01734       }
01735       *psd = temp;
01736     }
01737   }
01738 }
01739 
01740 static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
01741 {
01742   const ParentSpriteToDraw * const *psd_end = psd->End();
01743   for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
01744     const ParentSpriteToDraw *ps = *it;
01745     if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSprite(ps->image, ps->pal, ps->x, ps->y, ps->sub);
01746 
01747     int child_idx = ps->first_child;
01748     while (child_idx >= 0) {
01749       const ChildScreenSpriteToDraw *cs = csstdv->Get(child_idx);
01750       child_idx = cs->next;
01751       DrawSprite(cs->image, cs->pal, ps->left + cs->x, ps->top + cs->y, cs->sub);
01752     }
01753   }
01754 }
01755 
01760 static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
01761 {
01762   const ParentSpriteToDraw * const *psd_end = psd->End();
01763   for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
01764     const ParentSpriteToDraw *ps = *it;
01765     Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner
01766     Point pt2 = RemapCoords(ps->xmin    , ps->ymax + 1, ps->zmax + 1); // top left corner
01767     Point pt3 = RemapCoords(ps->xmax + 1, ps->ymin    , ps->zmax + 1); // top right corner
01768     Point pt4 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmin    ); // bottom front corner
01769 
01770     DrawBox(        pt1.x,         pt1.y,
01771             pt2.x - pt1.x, pt2.y - pt1.y,
01772             pt3.x - pt1.x, pt3.y - pt1.y,
01773             pt4.x - pt1.x, pt4.y - pt1.y);
01774   }
01775 }
01776 
01777 static void ViewportDrawStrings(DrawPixelInfo *dpi, const StringSpriteToDrawVector *sstdv)
01778 {
01779   DrawPixelInfo dp;
01780   ZoomLevel zoom;
01781 
01782   _cur_dpi = &dp;
01783   dp = *dpi;
01784 
01785   zoom = dp.zoom;
01786   dp.zoom = ZOOM_LVL_NORMAL;
01787 
01788   dp.left   = UnScaleByZoom(dp.left,   zoom);
01789   dp.top    = UnScaleByZoom(dp.top,    zoom);
01790   dp.width  = UnScaleByZoom(dp.width,  zoom);
01791   dp.height = UnScaleByZoom(dp.height, zoom);
01792 
01793   const StringSpriteToDraw *ssend = sstdv->End();
01794   for (const StringSpriteToDraw *ss = sstdv->Begin(); ss != ssend; ++ss) {
01795     TextColour colour = TC_BLACK;
01796     bool small = HasBit(ss->width, 15);
01797     int w = GB(ss->width, 0, 15);
01798     int x = UnScaleByZoom(ss->x, zoom);
01799     int y = UnScaleByZoom(ss->y, zoom);
01800     int h = VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM;
01801 
01802     SetDParam(0, ss->params[0]);
01803     SetDParam(1, ss->params[1]);
01804 
01805     if (ss->colour != INVALID_COLOUR) {
01806       /* Do not draw signs nor station names if they are set invisible */
01807       if (IsInvisibilitySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) continue;
01808 
01809       /* if we didn't draw a rectangle, or if transparant building is on,
01810        * draw the text in the colour the rectangle would have */
01811       if (IsTransparencySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) {
01812         /* Real colours need the TC_IS_PALETTE_COLOUR flag
01813          * otherwise colours from _string_colourmap are assumed. */
01814         colour = (TextColour)_colour_gradient[ss->colour][6] | TC_IS_PALETTE_COLOUR;
01815       }
01816 
01817       /* Draw the rectangle if 'tranparent station signs' is off,
01818        * or if we are drawing a general text sign (STR_WHITE_SIGN) */
01819       if (!IsTransparencySet(TO_SIGNS) || ss->string == STR_WHITE_SIGN) {
01820         DrawFrameRect(
01821           x, y, x + w, y + h, ss->colour,
01822           IsTransparencySet(TO_SIGNS) ? FR_TRANSPARENT : FR_NONE
01823         );
01824       }
01825     }
01826 
01827     DrawString(x + VPSM_LEFT, x + w - 1 - VPSM_RIGHT, y + VPSM_TOP, ss->string, colour, SA_HOR_CENTER);
01828   }
01829 }
01830 
01831 void ViewportDoDraw(const ViewPort *vp, int left, int top, int right, int bottom)
01832 {
01833   DrawPixelInfo *old_dpi = _cur_dpi;
01834   _cur_dpi = &_vd.dpi;
01835 
01836   _vd.dpi.zoom = vp->zoom;
01837   int mask = ScaleByZoom(-1, vp->zoom);
01838 
01839   _vd.combine_sprites = SPRITE_COMBINE_NONE;
01840 
01841   _vd.dpi.width = (right - left) & mask;
01842   _vd.dpi.height = (bottom - top) & mask;
01843   _vd.dpi.left = left & mask;
01844   _vd.dpi.top = top & mask;
01845   _vd.dpi.pitch = old_dpi->pitch;
01846   _vd.last_child = NULL;
01847 
01848   int x = UnScaleByZoom(_vd.dpi.left - (vp->virtual_left & mask), vp->zoom) + vp->left;
01849   int y = UnScaleByZoom(_vd.dpi.top - (vp->virtual_top & mask), vp->zoom) + vp->top;
01850 
01851   _vd.dpi.dst_ptr = BlitterFactoryBase::GetCurrentBlitter()->MoveTo(old_dpi->dst_ptr, x - old_dpi->left, y - old_dpi->top);
01852 
01853   ViewportAddLandscape();
01854   ViewportAddVehicles(&_vd.dpi);
01855 
01856   ViewportAddTownNames(&_vd.dpi);
01857   ViewportAddStationNames(&_vd.dpi);
01858   ViewportAddSigns(&_vd.dpi);
01859 
01860   DrawTextEffects(&_vd.dpi);
01861 
01862   if (_vd.tile_sprites_to_draw.Length() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
01863 
01864   ParentSpriteToDraw *psd_end = _vd.parent_sprites_to_draw.End();
01865   for (ParentSpriteToDraw *it = _vd.parent_sprites_to_draw.Begin(); it != psd_end; it++) {
01866     *_vd.parent_sprites_to_sort.Append() = it;
01867   }
01868 
01869   ViewportSortParentSprites(&_vd.parent_sprites_to_sort);
01870   ViewportDrawParentSprites(&_vd.parent_sprites_to_sort, &_vd.child_screen_sprites_to_draw);
01871 
01872   if (_draw_bounding_boxes) ViewportDrawBoundingBoxes(&_vd.parent_sprites_to_sort);
01873 
01874   if (_vd.string_sprites_to_draw.Length() != 0) ViewportDrawStrings(&_vd.dpi, &_vd.string_sprites_to_draw);
01875 
01876   _cur_dpi = old_dpi;
01877 
01878   _vd.string_sprites_to_draw.Clear();
01879   _vd.tile_sprites_to_draw.Clear();
01880   _vd.parent_sprites_to_draw.Clear();
01881   _vd.parent_sprites_to_sort.Clear();
01882   _vd.child_screen_sprites_to_draw.Clear();
01883 }
01884 
01889 static void ViewportDrawChk(const ViewPort *vp, int left, int top, int right, int bottom)
01890 {
01891   if (ScaleByZoom(bottom - top, vp->zoom) * ScaleByZoom(right - left, vp->zoom) > 180000) {
01892     if ((bottom - top) > (right - left)) {
01893       int t = (top + bottom) >> 1;
01894       ViewportDrawChk(vp, left, top, right, t);
01895       ViewportDrawChk(vp, left, t, right, bottom);
01896     } else {
01897       int t = (left + right) >> 1;
01898       ViewportDrawChk(vp, left, top, t, bottom);
01899       ViewportDrawChk(vp, t, top, right, bottom);
01900     }
01901   } else {
01902     ViewportDoDraw(vp,
01903       ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
01904       ScaleByZoom(top - vp->top, vp->zoom) + vp->virtual_top,
01905       ScaleByZoom(right - vp->left, vp->zoom) + vp->virtual_left,
01906       ScaleByZoom(bottom - vp->top, vp->zoom) + vp->virtual_top
01907     );
01908   }
01909 }
01910 
01911 static inline void ViewportDraw(const ViewPort *vp, int left, int top, int right, int bottom)
01912 {
01913   if (right <= vp->left || bottom <= vp->top) return;
01914 
01915   if (left >= vp->left + vp->width) return;
01916 
01917   if (left < vp->left) left = vp->left;
01918   if (right > vp->left + vp->width) right = vp->left + vp->width;
01919 
01920   if (top >= vp->top + vp->height) return;
01921 
01922   if (top < vp->top) top = vp->top;
01923   if (bottom > vp->top + vp->height) bottom = vp->top + vp->height;
01924 
01925   ViewportDrawChk(vp, left, top, right, bottom);
01926 }
01927 
01931 void Window::DrawViewport() const
01932 {
01933   DrawPixelInfo *dpi = _cur_dpi;
01934 
01935   dpi->left += this->left;
01936   dpi->top += this->top;
01937 
01938   ViewportDraw(this->viewport, dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height);
01939 
01940   dpi->left -= this->left;
01941   dpi->top -= this->top;
01942 }
01943 
01949 uint16 GetMaxScrollOutsideMap() {
01950   /* Allow scrolling to high peaks at the NE/NW border if AllowMoreHeightlevels is true. */
01951   if (AllowMoreHeightlevels()) {
01952     return MAXSCROLL_NEW;
01953   } else {
01954     return MAXSCROLL_OLD;
01955   }
01956 }
01957 
01958 static inline void ClampViewportToMap(const ViewPort *vp, int &x, int &y)
01959 {
01960   /* Centre of the viewport is hot spot */
01961   x += vp->virtual_width / 2;
01962   y += vp->virtual_height / 2;
01963 
01964   /* Convert viewport coordinates to map coordinates
01965    * Calculation is scaled by 4 to avoid rounding errors */
01966   int vx = -x + y * 2;
01967   int vy =  x + y * 2;
01968 
01969   /* Clamp to size of map. */
01970   vx = Clamp(vx, - (uint16)GetMaxScrollOutsideMap(), MapMaxX() * TILE_SIZE * 4);
01971   vy = Clamp(vy, - (uint16)GetMaxScrollOutsideMap(), MapMaxY() * TILE_SIZE * 4);
01972 
01973   /* Convert map coordinates to viewport coordinates */
01974   x = (-vx + vy) / 2;
01975   y = ( vx + vy) / 4;
01976 
01977   /* Remove centering */
01978   x -= vp->virtual_width / 2;
01979   y -= vp->virtual_height / 2;
01980 }
01981 
01986 void UpdateViewportPosition(Window *w)
01987 {
01988   const ViewPort *vp = w->viewport;
01989 
01990   if (w->viewport->follow_vehicle != INVALID_VEHICLE) {
01991     const Vehicle *veh = Vehicle::Get(w->viewport->follow_vehicle);
01992     Point pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
01993 
01994     w->viewport->scrollpos_x = pt.x;
01995     w->viewport->scrollpos_y = pt.y;
01996     SetViewportPosition(w, pt.x, pt.y);
01997   } else {
01998     /* Ensure the destination location is within the map */
01999     ClampViewportToMap(vp, w->viewport->dest_scrollpos_x, w->viewport->dest_scrollpos_y);
02000 
02001     int delta_x = w->viewport->dest_scrollpos_x - w->viewport->scrollpos_x;
02002     int delta_y = w->viewport->dest_scrollpos_y - w->viewport->scrollpos_y;
02003 
02004     if (delta_x != 0 || delta_y != 0) {
02005       if (_settings_client.gui.smooth_scroll) {
02006         int max_scroll = ScaleByMapSize1D(512);
02007         /* Not at our desired position yet... */
02008         w->viewport->scrollpos_x += Clamp(delta_x / 4, -max_scroll, max_scroll);
02009         w->viewport->scrollpos_y += Clamp(delta_y / 4, -max_scroll, max_scroll);
02010       } else {
02011         w->viewport->scrollpos_x = w->viewport->dest_scrollpos_x;
02012         w->viewport->scrollpos_y = w->viewport->dest_scrollpos_y;
02013       }
02014     }
02015 
02016     ClampViewportToMap(vp, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
02017 
02018     SetViewportPosition(w, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
02019   }
02020 }
02021 
02031 static void MarkViewportDirty(const ViewPort *vp, int left, int top, int right, int bottom)
02032 {
02033   right -= vp->virtual_left;
02034   if (right <= 0) return;
02035 
02036   bottom -= vp->virtual_top;
02037   if (bottom <= 0) return;
02038 
02039   left = max(0, left - vp->virtual_left);
02040 
02041   if (left >= vp->virtual_width) return;
02042 
02043   top = max(0, top - vp->virtual_top);
02044 
02045   if (top >= vp->virtual_height) return;
02046 
02047   SetDirtyBlocks(
02048     UnScaleByZoomLower(left, vp->zoom) + vp->left,
02049     UnScaleByZoomLower(top, vp->zoom) + vp->top,
02050     UnScaleByZoom(right, vp->zoom) + vp->left + 1,
02051     UnScaleByZoom(bottom, vp->zoom) + vp->top + 1
02052   );
02053 }
02054 
02063 void MarkAllViewportsDirty(int left, int top, int right, int bottom)
02064 {
02065   Window *w;
02066   FOR_ALL_WINDOWS_FROM_BACK(w) {
02067     ViewPort *vp = w->viewport;
02068     if (vp != NULL) {
02069       assert(vp->width != 0);
02070       MarkViewportDirty(vp, left, top, right, bottom);
02071     }
02072   }
02073 }
02074 
02080 void MarkTileDirtyByTile(TileIndex tile)
02081 {
02082   Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, GetTileZ(tile));
02083   MarkAllViewportsDirty(
02084     pt.x - 31,
02085     pt.y - 122,
02086     pt.x - 31 + 67,
02087     pt.y - 122 + 154
02088   );
02089 }
02090 
02091 void MarkTileDirtyByTileOutsideMap(int x, int y)
02092 {
02093   Point pt = RemapCoords(x * TILE_SIZE, y * TILE_SIZE, GetTileZOutsideMap(x, y));
02094   /* Since tiles painted outside the map don't contain buildings, trees, etc.,
02095    * this reduced area for repainting should suffice. If not, adjust the offsets
02096    * used below. */
02097   MarkAllViewportsDirty(
02098     pt.x - TILE_SIZE + 1,
02099     pt.y,
02100     pt.x + TILE_SIZE - 1,
02101     pt.y + TILE_SIZE + TILE_HEIGHT - 1
02102   );
02103 }
02104 
02112 static void SetSelectionTilesDirty()
02113 {
02114   int x_size = _thd.size.x;
02115   int y_size = _thd.size.y;
02116 
02117   if (!_thd.diagonal) { // Selecting in a straigth rectangle (or a single square)
02118     int x_start = _thd.pos.x;
02119     int y_start = _thd.pos.y;
02120 
02121     if (_thd.outersize.x != 0) {
02122       x_size  += _thd.outersize.x;
02123       x_start += _thd.offs.x;
02124       y_size  += _thd.outersize.y;
02125       y_start += _thd.offs.y;
02126     }
02127 
02128     x_size -= TILE_SIZE;
02129     y_size -= TILE_SIZE;
02130 
02131     assert(x_size >= 0);
02132     assert(y_size >= 0);
02133 
02134     int x_end = Clamp(x_start + x_size, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
02135     int y_end = Clamp(y_start + y_size, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
02136 
02137     x_start = Clamp(x_start, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
02138     y_start = Clamp(y_start, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
02139 
02140     /* make sure everything is multiple of TILE_SIZE */
02141     assert((x_end | y_end | x_start | y_start) % TILE_SIZE == 0);
02142 
02143     /* How it works:
02144      * Suppose we have to mark dirty rectangle of 3x4 tiles:
02145      *   x
02146      *  xxx
02147      * xxxxx
02148      *  xxxxx
02149      *   xxx
02150      *    x
02151      * This algorithm marks dirty columns of tiles, so it is done in 3+4-1 steps:
02152      * 1)  x     2)  x
02153      *    xxx       Oxx
02154      *   Oxxxx     xOxxx
02155      *    xxxxx     Oxxxx
02156      *     xxx       xxx
02157      *      x         x
02158      * And so forth...
02159      */
02160 
02161     int top_x = x_end; // coordinates of top dirty tile
02162     int top_y = y_start;
02163     int bot_x = top_x; // coordinates of bottom dirty tile
02164     int bot_y = top_y;
02165 
02166     do {
02167       Point top = RemapCoords2(top_x, top_y); // topmost dirty point
02168       Point bot = RemapCoords2(bot_x + TILE_SIZE - 1, bot_y + TILE_SIZE - 1); // bottommost point
02169 
02170       /* the 'x' coordinate of 'top' and 'bot' is the same (and always in the same distance from tile middle),
02171        * tile height/slope affects only the 'y' on-screen coordinate! */
02172 
02173       int l = top.x - (TILE_PIXELS - 2); // 'x' coordinate of left side of dirty rectangle
02174       int t = top.y;                     // 'y' coordinate of top side -//-
02175       int r = top.x + (TILE_PIXELS - 2); // right side of dirty rectangle
02176       int b = bot.y;                     // bottom -//-
02177 
02178       static const int OVERLAY_WIDTH = 4; // part of selection sprites is drawn outside the selected area
02179 
02180       /* For halftile foundations on SLOPE_STEEP_S the sprite extents some more towards the top */
02181       MarkAllViewportsDirty(l - OVERLAY_WIDTH, t - OVERLAY_WIDTH - TILE_HEIGHT, r + OVERLAY_WIDTH, b + OVERLAY_WIDTH);
02182 
02183       /* haven't we reached the topmost tile yet? */
02184       if (top_x != x_start) {
02185         top_x -= TILE_SIZE;
02186       } else {
02187         top_y += TILE_SIZE;
02188       }
02189 
02190       /* the way the bottom tile changes is different when we reach the bottommost tile */
02191       if (bot_y != y_end) {
02192         bot_y += TILE_SIZE;
02193       } else {
02194         bot_x -= TILE_SIZE;
02195       }
02196     } while (bot_x >= top_x);
02197   } else { // Selecting in a 45 degrees rotated (diagonal) rectangle.
02198     /* a_size, b_size describe a rectangle with rotated coordinates */
02199     int a_size = x_size + y_size, b_size = x_size - y_size;
02200 
02201     int interval_a = a_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
02202     int interval_b = b_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
02203 
02204     for (int a = -interval_a; a != a_size + interval_a; a += interval_a) {
02205       for (int b = -interval_b; b != b_size + interval_b; b += interval_b) {
02206         uint x = (_thd.pos.x + (a + b) / 2) / TILE_SIZE;
02207         uint y = (_thd.pos.y + (a - b) / 2) / TILE_SIZE;
02208 
02209         if (x < MapMaxX() && y < MapMaxY()) {
02210           MarkTileDirtyByTile(TileXY(x, y));
02211         }
02212       }
02213     }
02214   }
02215 }
02216 
02217 
02218 void SetSelectionRed(bool b)
02219 {
02220   _thd.make_square_red = b;
02221   SetSelectionTilesDirty();
02222 }
02223 
02232 static bool CheckClickOnViewportSign(const ViewPort *vp, int x, int y, const ViewportSign *sign)
02233 {
02234   bool small = (vp->zoom >= ZOOM_LVL_OUT_4X);
02235   int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, vp->zoom);
02236   int sign_height = ScaleByZoom(VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM, vp->zoom);
02237 
02238   x = ScaleByZoom(x - vp->left, vp->zoom) + vp->virtual_left;
02239   y = ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top;
02240 
02241   return y >= sign->top && y < sign->top + sign_height &&
02242       x >= sign->center - sign_half_width && x < sign->center + sign_half_width;
02243 }
02244 
02245 static bool CheckClickOnTown(const ViewPort *vp, int x, int y)
02246 {
02247   if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES)) return false;
02248 
02249   const Town *t;
02250   FOR_ALL_TOWNS(t) {
02251     if (CheckClickOnViewportSign(vp, x, y, &t->sign)) {
02252       ShowTownViewWindow(t->index);
02253       return true;
02254     }
02255   }
02256 
02257   return false;
02258 }
02259 
02260 static bool CheckClickOnStation(const ViewPort *vp, int x, int y)
02261 {
02262   if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || IsInvisibilitySet(TO_SIGNS)) return false;
02263 
02264   const BaseStation *st;
02265   FOR_ALL_BASE_STATIONS(st) {
02266     /* Check whether the base station is a station or a waypoint */
02267     bool is_station = Station::IsExpected(st);
02268 
02269     /* Don't check if the display options are disabled */
02270     if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
02271 
02272     if (CheckClickOnViewportSign(vp, x, y, &st->sign)) {
02273       if (is_station) {
02274         ShowStationViewWindow(st->index);
02275       } else {
02276         ShowWaypointWindow(Waypoint::From(st));
02277       }
02278       return true;
02279     }
02280   }
02281 
02282   return false;
02283 }
02284 
02285 
02286 static bool CheckClickOnSign(const ViewPort *vp, int x, int y)
02287 {
02288   /* Signs are turned off, or they are transparent and invisibility is ON, or company is a spectator */
02289   if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS) || _local_company == COMPANY_SPECTATOR) return false;
02290 
02291   const Sign *si;
02292   FOR_ALL_SIGNS(si) {
02293     if (CheckClickOnViewportSign(vp, x, y, &si->sign)) {
02294       HandleClickOnSign(si);
02295       return true;
02296     }
02297   }
02298 
02299   return false;
02300 }
02301 
02302 
02303 static bool CheckClickOnLandscape(const ViewPort *vp, int x, int y)
02304 {
02305   Point pt = TranslateXYToTileCoord(vp, x, y);
02306 
02307   if (pt.x != -1) return ClickTile(TileVirtXY(pt.x, pt.y));
02308   return true;
02309 }
02310 
02311 static void PlaceObject()
02312 {
02313   Point pt;
02314   Window *w;
02315 
02316   pt = GetTileBelowCursor();
02317   if (pt.x == -1) return;
02318 
02319   if ((_thd.place_mode & HT_DRAG_MASK) == HT_POINT) {
02320     pt.x += 8;
02321     pt.y += 8;
02322   }
02323 
02324   _tile_fract_coords.x = pt.x & TILE_UNIT_MASK;
02325   _tile_fract_coords.y = pt.y & TILE_UNIT_MASK;
02326 
02327   w = _thd.GetCallbackWnd();
02328   if (w != NULL) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
02329 }
02330 
02331 
02332 bool HandleViewportClicked(const ViewPort *vp, int x, int y)
02333 {
02334   const Vehicle *v = CheckClickOnVehicle(vp, x, y);
02335 
02336   if (_thd.place_mode & HT_VEHICLE) {
02337     if (v != NULL && VehicleClicked(v)) return true;
02338   }
02339 
02340   /* Vehicle placement mode already handled above. */
02341   if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
02342     PlaceObject();
02343     return true;
02344   }
02345 
02346   if (CheckClickOnTown(vp, x, y)) return true;
02347   if (CheckClickOnStation(vp, x, y)) return true;
02348   if (CheckClickOnSign(vp, x, y)) return true;
02349   bool result = CheckClickOnLandscape(vp, x, y);
02350 
02351   if (v != NULL) {
02352     DEBUG(misc, 2, "Vehicle %d (index %d) at %p", v->unitnumber, v->index, v);
02353     if (IsCompanyBuildableVehicleType(v)) {
02354       v = v->First();
02355       if (_ctrl_pressed && v->owner == _local_company) {
02356         StartStopVehicle(v, true);
02357       } else {
02358         ShowVehicleViewWindow(v);
02359       }
02360     }
02361     return true;
02362   }
02363   return result;
02364 }
02365 
02366 
02376 bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
02377 {
02378   /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
02379   if (z == -1) {
02380     if ( x >= 0 && x <= (int)MapSizeX() * (int)TILE_SIZE - 1
02381         && y >= 0 && y <= (int)MapSizeY() * (int)TILE_SIZE - 1) {
02382       z = GetSlopeZ(x, y);
02383     } else {
02384       z = TileHeightOutsideMap(x / TILE_SIZE, y / TILE_SIZE);
02385     }
02386   }
02387 
02388   Point pt = MapXYZToViewport(w->viewport, x, y, z);
02389   w->viewport->follow_vehicle = INVALID_VEHICLE;
02390 
02391   if (w->viewport->dest_scrollpos_x == pt.x && w->viewport->dest_scrollpos_y == pt.y) return false;
02392 
02393   if (instant) {
02394     w->viewport->scrollpos_x = pt.x;
02395     w->viewport->scrollpos_y = pt.y;
02396   }
02397 
02398   w->viewport->dest_scrollpos_x = pt.x;
02399   w->viewport->dest_scrollpos_y = pt.y;
02400   return true;
02401 }
02402 
02410 bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
02411 {
02412   return ScrollWindowTo(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, -1, w, instant);
02413 }
02414 
02421 bool ScrollMainWindowToTile(TileIndex tile, bool instant)
02422 {
02423   return ScrollMainWindowTo(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, -1, instant);
02424 }
02425 
02430 void SetRedErrorSquare(TileIndex tile)
02431 {
02432   TileIndex old;
02433 
02434   old = _thd.redsq;
02435   _thd.redsq = tile;
02436 
02437   if (tile != old) {
02438     if (tile != INVALID_TILE) MarkTileDirtyByTile(tile);
02439     if (old  != INVALID_TILE) MarkTileDirtyByTile(old);
02440   }
02441 }
02442 
02448 void SetTileSelectSize(int w, int h)
02449 {
02450   _thd.new_size.x = w * TILE_SIZE;
02451   _thd.new_size.y = h * TILE_SIZE;
02452   _thd.new_outersize.x = 0;
02453   _thd.new_outersize.y = 0;
02454 }
02455 
02456 void SetTileSelectBigSize(int ox, int oy, int sx, int sy)
02457 {
02458   _thd.offs.x = ox * TILE_SIZE;
02459   _thd.offs.y = oy * TILE_SIZE;
02460   _thd.new_outersize.x = sx * TILE_SIZE;
02461   _thd.new_outersize.y = sy * TILE_SIZE;
02462 }
02463 
02465 static HighLightStyle GetAutorailHT(int x, int y)
02466 {
02467   return HT_RAIL | _autorail_piece[x & TILE_UNIT_MASK][y & TILE_UNIT_MASK];
02468 }
02469 
02473 void TileHighlightData::Reset()
02474 {
02475   this->pos.x = 0;
02476   this->pos.y = 0;
02477   this->new_pos.x = 0;
02478   this->new_pos.y = 0;
02479 }
02480 
02485 bool TileHighlightData::IsDraggingDiagonal()
02486 {
02487   return (this->place_mode & HT_DIAGONAL) != 0 && _ctrl_pressed && _left_button_down;
02488 }
02489 
02494 Window *TileHighlightData::GetCallbackWnd()
02495 {
02496   return FindWindowById(this->window_class, this->window_number);
02497 }
02498 
02499 
02500 
02508 void UpdateTileSelection()
02509 {
02510   int x1;
02511   int y1;
02512 
02513   HighLightStyle new_drawstyle = HT_NONE;
02514   bool new_diagonal = false;
02515 
02516   if ((_thd.place_mode & HT_DRAG_MASK) == HT_SPECIAL) {
02517     x1 = _thd.selend.x;
02518     y1 = _thd.selend.y;
02519     if (x1 != -1) {
02520       int x2 = _thd.selstart.x & ~TILE_UNIT_MASK;
02521       int y2 = _thd.selstart.y & ~TILE_UNIT_MASK;
02522       x1 &= ~TILE_UNIT_MASK;
02523       y1 &= ~TILE_UNIT_MASK;
02524 
02525       if (_thd.IsDraggingDiagonal()) {
02526         new_diagonal = true;
02527       } else {
02528         if (x1 >= x2) Swap(x1, x2);
02529         if (y1 >= y2) Swap(y1, y2);
02530       }
02531       _thd.new_pos.x = x1;
02532       _thd.new_pos.y = y1;
02533       _thd.new_size.x = x2 - x1;
02534       _thd.new_size.y = y2 - y1;
02535       if (!new_diagonal) {
02536         _thd.new_size.x += TILE_SIZE;
02537         _thd.new_size.y += TILE_SIZE;
02538       }
02539       new_drawstyle = _thd.next_drawstyle;
02540     }
02541   } else if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
02542     Point pt = GetTileBelowCursor();
02543     x1 = pt.x;
02544     y1 = pt.y;
02545     if (x1 != -1) {
02546       switch (_thd.place_mode & HT_DRAG_MASK) {
02547         case HT_RECT:
02548           new_drawstyle = HT_RECT;
02549           break;
02550         case HT_POINT:
02551           new_drawstyle = HT_POINT;
02552           x1 += TILE_SIZE / 2;
02553           y1 += TILE_SIZE / 2;
02554           break;
02555         case HT_RAIL:
02556           /* Draw one highlighted tile in any direction */
02557           new_drawstyle = GetAutorailHT(pt.x, pt.y);
02558           break;
02559         case HT_LINE:
02560           switch (_thd.place_mode & HT_DIR_MASK) {
02561             case HT_DIR_X: new_drawstyle = HT_LINE | HT_DIR_X; break;
02562             case HT_DIR_Y: new_drawstyle = HT_LINE | HT_DIR_Y; break;
02563 
02564             case HT_DIR_HU:
02565             case HT_DIR_HL:
02566               new_drawstyle = (pt.x & TILE_UNIT_MASK) + (pt.y & TILE_UNIT_MASK) <= TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
02567               break;
02568 
02569             case HT_DIR_VL:
02570             case HT_DIR_VR:
02571               new_drawstyle = (pt.x & TILE_UNIT_MASK) > (pt.y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
02572               break;
02573 
02574             default: NOT_REACHED();
02575           }
02576           _thd.selstart.x = x1 & ~TILE_UNIT_MASK;
02577           _thd.selstart.y = y1 & ~TILE_UNIT_MASK;
02578           break;
02579         case HT_PREVIEW:
02580           new_drawstyle = HT_PREVIEW & HT_DRAG_MASK;
02581           break;
02582         default:
02583           NOT_REACHED();
02584           break;
02585       }
02586       _thd.new_pos.x = x1 & ~TILE_UNIT_MASK;
02587       _thd.new_pos.y = y1 & ~TILE_UNIT_MASK;
02588     }
02589   }
02590 
02591   /* redraw selection */
02592   if (_thd.drawstyle != new_drawstyle ||
02593       _thd.pos.x != _thd.new_pos.x || _thd.pos.y != _thd.new_pos.y ||
02594       _thd.size.x != _thd.new_size.x || _thd.size.y != _thd.new_size.y ||
02595       _thd.outersize.x != _thd.new_outersize.x ||
02596       _thd.outersize.y != _thd.new_outersize.y ||
02597       _thd.diagonal    != new_diagonal) {
02598     /* Clear the old tile selection? */
02599     if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
02600 
02601     _thd.drawstyle = new_drawstyle;
02602     _thd.pos = _thd.new_pos;
02603     _thd.size = _thd.new_size;
02604     _thd.outersize = _thd.new_outersize;
02605     _thd.diagonal = new_diagonal;
02606     _thd.dirty = 0xff;
02607 
02608     /* Draw the new tile selection? */
02609     if ((new_drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
02610   }
02611 }
02612 
02620 static inline void ShowMeasurementTooltips(StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_cond = TCC_LEFT_CLICK)
02621 {
02622   if (!_settings_client.gui.measure_tooltip) return;
02623   GuiShowTooltips(_thd.GetCallbackWnd(), str, paramcount, params, close_cond);
02624 }
02625 
02627 void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
02628 {
02629   _thd.select_method = method;
02630   _thd.select_proc   = process;
02631   _thd.selend.x = TileX(tile) * TILE_SIZE;
02632   _thd.selstart.x = TileX(tile) * TILE_SIZE;
02633   _thd.selend.y = TileY(tile) * TILE_SIZE;
02634   _thd.selstart.y = TileY(tile) * TILE_SIZE;
02635 
02636   /* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
02637    * In effect, placement starts from the centre of a tile
02638    */
02639   if (method == VPM_X_OR_Y || method == VPM_FIX_X || method == VPM_FIX_Y) {
02640     _thd.selend.x += TILE_SIZE / 2;
02641     _thd.selend.y += TILE_SIZE / 2;
02642     _thd.selstart.x += TILE_SIZE / 2;
02643     _thd.selstart.y += TILE_SIZE / 2;
02644   }
02645 
02646   HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
02647   if ((_thd.place_mode & HT_DRAG_MASK) == HT_RECT) {
02648     _thd.place_mode = HT_SPECIAL | others;
02649     _thd.next_drawstyle = HT_RECT | others;
02650   } else if (_thd.place_mode & (HT_RAIL | HT_LINE)) {
02651     _thd.place_mode = HT_SPECIAL | others;
02652     _thd.next_drawstyle = _thd.drawstyle | others;
02653   } else {
02654     _thd.place_mode = HT_SPECIAL | others;
02655     _thd.next_drawstyle = HT_POINT | others;
02656   }
02657   _special_mouse_mode = WSM_SIZING;
02658 }
02659 
02660 void VpSetPlaceSizingLimit(int limit)
02661 {
02662   _thd.sizelimit = limit;
02663 }
02664 
02670 void VpSetPresizeRange(TileIndex from, TileIndex to)
02671 {
02672   uint64 distance = DistanceManhattan(from, to) + 1;
02673 
02674   _thd.selend.x = TileX(to) * TILE_SIZE;
02675   _thd.selend.y = TileY(to) * TILE_SIZE;
02676   _thd.selstart.x = TileX(from) * TILE_SIZE;
02677   _thd.selstart.y = TileY(from) * TILE_SIZE;
02678   _thd.next_drawstyle = HT_RECT;
02679 
02680   /* show measurement only if there is any length to speak of */
02681   if (distance > 1) ShowMeasurementTooltips(STR_MEASURE_LENGTH, 1, &distance, TCC_HOVER);
02682 }
02683 
02684 static void VpStartPreSizing()
02685 {
02686   _thd.selend.x = -1;
02687   _special_mouse_mode = WSM_PRESIZE;
02688 }
02689 
02694 static HighLightStyle Check2x1AutoRail(int mode)
02695 {
02696   int fxpy = _tile_fract_coords.x + _tile_fract_coords.y;
02697   int sxpy = (_thd.selend.x & TILE_UNIT_MASK) + (_thd.selend.y & TILE_UNIT_MASK);
02698   int fxmy = _tile_fract_coords.x - _tile_fract_coords.y;
02699   int sxmy = (_thd.selend.x & TILE_UNIT_MASK) - (_thd.selend.y & TILE_UNIT_MASK);
02700 
02701   switch (mode) {
02702     default: NOT_REACHED();
02703     case 0: // end piece is lower right
02704       if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
02705       if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
02706       return HT_DIR_Y;
02707 
02708     case 1:
02709       if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
02710       if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
02711       return HT_DIR_Y;
02712 
02713     case 2:
02714       if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
02715       if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
02716       return HT_DIR_X;
02717 
02718     case 3:
02719       if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
02720       if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
02721       return HT_DIR_X;
02722   }
02723 }
02724 
02738 static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
02739 {
02740   uint start_x = TileX(start_tile);
02741   uint start_y = TileY(start_tile);
02742   uint end_x = TileX(end_tile);
02743   uint end_y = TileY(end_tile);
02744 
02745   switch (style & HT_DRAG_MASK) {
02746     case HT_RAIL:
02747     case HT_LINE: return (end_x > start_x || (end_x == start_x && end_y > start_y));
02748 
02749     case HT_RECT:
02750     case HT_POINT: return (end_x != start_x && end_y < start_y);
02751     default: NOT_REACHED();
02752   }
02753 
02754   return false;
02755 }
02756 
02772 static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
02773 {
02774   bool swap = SwapDirection(style, start_tile, end_tile);
02775   uint h0, h1; // Start height and end height.
02776 
02777   if (start_tile == end_tile) return 0;
02778   if (swap) Swap(start_tile, end_tile);
02779 
02780   switch (style & HT_DRAG_MASK) {
02781     case HT_RECT: {
02782       static const TileIndexDiffC heightdiff_area_by_dir[] = {
02783         /* Start */ {1, 0}, /* Dragging east */ {0, 0}, // Dragging south
02784         /* End   */ {0, 1}, /* Dragging east */ {1, 1}  // Dragging south
02785       };
02786 
02787       /* In the case of an area we can determine whether we were dragging south or
02788        * east by checking the X-coordinates of the tiles */
02789       byte style_t = (byte)(TileX(end_tile) > TileX(start_tile));
02790       start_tile = TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_area_by_dir[style_t]));
02791       end_tile   = TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_area_by_dir[2 + style_t]));
02792       /* FALL THROUGH */
02793     }
02794 
02795     case HT_POINT:
02796       h0 = TileHeight(start_tile);
02797       h1 = TileHeight(end_tile);
02798       break;
02799     default: { // All other types, this is mostly only line/autorail
02800       static const HighLightStyle flip_style_direction[] = {
02801         HT_DIR_X, HT_DIR_Y, HT_DIR_HL, HT_DIR_HU, HT_DIR_VR, HT_DIR_VL
02802       };
02803       static const TileIndexDiffC heightdiff_line_by_dir[] = {
02804         /* Start */ {1, 0}, {1, 1}, /* HT_DIR_X  */ {0, 1}, {1, 1}, // HT_DIR_Y
02805         /* Start */ {1, 0}, {0, 0}, /* HT_DIR_HU */ {1, 0}, {1, 1}, // HT_DIR_HL
02806         /* Start */ {1, 0}, {1, 1}, /* HT_DIR_VL */ {0, 1}, {1, 1}, // HT_DIR_VR
02807 
02808         /* Start */ {0, 1}, {0, 0}, /* HT_DIR_X  */ {1, 0}, {0, 0}, // HT_DIR_Y
02809         /* End   */ {0, 1}, {0, 0}, /* HT_DIR_HU */ {1, 1}, {0, 1}, // HT_DIR_HL
02810         /* End   */ {1, 0}, {0, 0}, /* HT_DIR_VL */ {0, 0}, {0, 1}, // HT_DIR_VR
02811       };
02812 
02813       distance %= 2; // we're only interested if the distance is even or uneven
02814       style &= HT_DIR_MASK;
02815 
02816       /* To handle autorail, we do some magic to be able to use a lookup table.
02817        * Firstly if we drag the other way around, we switch start&end, and if needed
02818        * also flip the drag-position. Eg if it was on the left, and the distance is even
02819        * that means the end, which is now the start is on the right */
02820       if (swap && distance == 0) style = flip_style_direction[style];
02821 
02822       /* Use lookup table for start-tile based on HighLightStyle direction */
02823       byte style_t = style * 2;
02824       assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
02825       h0 = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t])));
02826       uint ht = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t + 1])));
02827       h0 = max(h0, ht);
02828 
02829       /* Use lookup table for end-tile based on HighLightStyle direction
02830        * flip around side (lower/upper, left/right) based on distance */
02831       if (distance == 0) style_t = flip_style_direction[style] * 2;
02832       assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
02833       h1 = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t])));
02834       ht = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t + 1])));
02835       h1 = max(h1, ht);
02836       break;
02837     }
02838   }
02839 
02840   if (swap) Swap(h0, h1);
02841   return (int)(h1 - h0) * TILE_HEIGHT_STEP;
02842 }
02843 
02844 static const StringID measure_strings_length[] = {STR_NULL, STR_MEASURE_LENGTH, STR_MEASURE_LENGTH_HEIGHTDIFF};
02845 
02852 static void CheckUnderflow(int &test, int &other, int mult)
02853 {
02854   if (test >= 0) return;
02855 
02856   other += mult * test;
02857   test = 0;
02858 }
02859 
02867 static void CheckOverflow(int &test, int &other, int max, int mult)
02868 {
02869   if (test <= max) return;
02870 
02871   other += mult * (test - max);
02872   test = max;
02873 }
02874 
02876 static void CalcRaildirsDrawstyle(int x, int y, int method)
02877 {
02878   HighLightStyle b;
02879 
02880   int dx = _thd.selstart.x - (_thd.selend.x & ~TILE_UNIT_MASK);
02881   int dy = _thd.selstart.y - (_thd.selend.y & ~TILE_UNIT_MASK);
02882   uint w = abs(dx) + TILE_SIZE;
02883   uint h = abs(dy) + TILE_SIZE;
02884 
02885   if (method & ~(VPM_RAILDIRS | VPM_SIGNALDIRS)) {
02886     /* We 'force' a selection direction; first four rail buttons. */
02887     method &= ~(VPM_RAILDIRS | VPM_SIGNALDIRS);
02888     int raw_dx = _thd.selstart.x - _thd.selend.x;
02889     int raw_dy = _thd.selstart.y - _thd.selend.y;
02890     switch (method) {
02891       case VPM_FIX_X:
02892         b = HT_LINE | HT_DIR_Y;
02893         x = _thd.selstart.x;
02894         break;
02895 
02896       case VPM_FIX_Y:
02897         b = HT_LINE | HT_DIR_X;
02898         y = _thd.selstart.y;
02899         break;
02900 
02901       case VPM_FIX_HORIZONTAL:
02902         if (dx == -dy) {
02903           /* We are on a straight horizontal line. Determine the 'rail'
02904            * to build based the sub tile location. */
02905           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
02906         } else {
02907           /* We are not on a straight line. Determine the rail to build
02908            * based on whether we are above or below it. */
02909           b = dx + dy >= (int)TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
02910 
02911           /* Calculate where a horizontal line through the start point and
02912            * a vertical line from the selected end point intersect and
02913            * use that point as the end point. */
02914           int offset = (raw_dx - raw_dy) / 2;
02915           x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
02916           y = _thd.selstart.y + (offset & ~TILE_UNIT_MASK);
02917 
02918           /* 'Build' the last half rail tile if needed */
02919           if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
02920             if (dx + dy >= (int)TILE_SIZE) {
02921               x += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
02922             } else {
02923               y += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
02924             }
02925           }
02926 
02927           /* Make sure we do not overflow the map! */
02928           CheckUnderflow(x, y, 1);
02929           CheckUnderflow(y, x, 1);
02930           CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, 1);
02931           CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, 1);
02932           assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
02933         }
02934         break;
02935 
02936       case VPM_FIX_VERTICAL:
02937         if (dx == dy) {
02938           /* We are on a straight vertical line. Determine the 'rail'
02939            * to build based the sub tile location. */
02940           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
02941         } else {
02942           /* We are not on a straight line. Determine the rail to build
02943            * based on whether we are left or right from it. */
02944           b = dx < dy ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
02945 
02946           /* Calculate where a vertical line through the start point and
02947            * a horizontal line from the selected end point intersect and
02948            * use that point as the end point. */
02949           int offset = (raw_dx + raw_dy + (int)TILE_SIZE) / 2;
02950           x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
02951           y = _thd.selstart.y - (offset & ~TILE_UNIT_MASK);
02952 
02953           /* 'Build' the last half rail tile if needed */
02954           if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
02955             if (dx - dy < 0) {
02956               y += (dx > dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
02957             } else {
02958               x += (dx < dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
02959             }
02960           }
02961 
02962           /* Make sure we do not overflow the map! */
02963           CheckUnderflow(x, y, -1);
02964           CheckUnderflow(y, x, -1);
02965           CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, -1);
02966           CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, -1);
02967           assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
02968         }
02969         break;
02970 
02971       default:
02972         NOT_REACHED();
02973     }
02974   } else if (TileVirtXY(_thd.selstart.x, _thd.selstart.y) == TileVirtXY(x, y)) { // check if we're only within one tile
02975     if (method & VPM_RAILDIRS) {
02976       b = GetAutorailHT(x, y);
02977     } else { // rect for autosignals on one tile
02978       b = HT_RECT;
02979     }
02980   } else if (h == TILE_SIZE) { // Is this in X direction?
02981     if (dx == (int)TILE_SIZE) { // 2x1 special handling
02982       b = (Check2x1AutoRail(3)) | HT_LINE;
02983     } else if (dx == -(int)TILE_SIZE) {
02984       b = (Check2x1AutoRail(2)) | HT_LINE;
02985     } else {
02986       b = HT_LINE | HT_DIR_X;
02987     }
02988     y = _thd.selstart.y;
02989   } else if (w == TILE_SIZE) { // Or Y direction?
02990     if (dy == (int)TILE_SIZE) { // 2x1 special handling
02991       b = (Check2x1AutoRail(1)) | HT_LINE;
02992     } else if (dy == -(int)TILE_SIZE) { // 2x1 other direction
02993       b = (Check2x1AutoRail(0)) | HT_LINE;
02994     } else {
02995       b = HT_LINE | HT_DIR_Y;
02996     }
02997     x = _thd.selstart.x;
02998   } else if (w > h * 2) { // still count as x dir?
02999     b = HT_LINE | HT_DIR_X;
03000     y = _thd.selstart.y;
03001   } else if (h > w * 2) { // still count as y dir?
03002     b = HT_LINE | HT_DIR_Y;
03003     x = _thd.selstart.x;
03004   } else { // complicated direction
03005     int d = w - h;
03006     _thd.selend.x = _thd.selend.x & ~TILE_UNIT_MASK;
03007     _thd.selend.y = _thd.selend.y & ~TILE_UNIT_MASK;
03008 
03009     /* four cases. */
03010     if (x > _thd.selstart.x) {
03011       if (y > _thd.selstart.y) {
03012         /* south */
03013         if (d == 0) {
03014           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
03015         } else if (d >= 0) {
03016           x = _thd.selstart.x + h;
03017           b = HT_LINE | HT_DIR_VL;
03018         } else {
03019           y = _thd.selstart.y + w;
03020           b = HT_LINE | HT_DIR_VR;
03021         }
03022       } else {
03023         /* west */
03024         if (d == 0) {
03025           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
03026         } else if (d >= 0) {
03027           x = _thd.selstart.x + h;
03028           b = HT_LINE | HT_DIR_HL;
03029         } else {
03030           y = _thd.selstart.y - w;
03031           b = HT_LINE | HT_DIR_HU;
03032         }
03033       }
03034     } else {
03035       if (y > _thd.selstart.y) {
03036         /* east */
03037         if (d == 0) {
03038           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
03039         } else if (d >= 0) {
03040           x = _thd.selstart.x - h;
03041           b = HT_LINE | HT_DIR_HU;
03042         } else {
03043           y = _thd.selstart.y + w;
03044           b = HT_LINE | HT_DIR_HL;
03045         }
03046       } else {
03047         /* north */
03048         if (d == 0) {
03049           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
03050         } else if (d >= 0) {
03051           x = _thd.selstart.x - h;
03052           b = HT_LINE | HT_DIR_VR;
03053         } else {
03054           y = _thd.selstart.y - w;
03055           b = HT_LINE | HT_DIR_VL;
03056         }
03057       }
03058     }
03059   }
03060 
03061   if (_settings_client.gui.measure_tooltip) {
03062     TileIndex t0 = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
03063     TileIndex t1 = TileVirtXY(x, y);
03064     uint distance = DistanceManhattan(t0, t1) + 1;
03065     byte index = 0;
03066     uint64 params[2];
03067 
03068     if (distance != 1) {
03069       int heightdiff = CalcHeightdiff(b, distance, t0, t1);
03070       /* If we are showing a tooltip for horizontal or vertical drags,
03071        * 2 tiles have a length of 1. To bias towards the ceiling we add
03072        * one before division. It feels more natural to count 3 lengths as 2 */
03073       if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
03074         distance = CeilDiv(distance, 2);
03075       }
03076 
03077       params[index++] = distance;
03078       if (heightdiff != 0) params[index++] = heightdiff;
03079     }
03080 
03081     ShowMeasurementTooltips(measure_strings_length[index], index, params);
03082   }
03083 
03084   _thd.selend.x = x;
03085   _thd.selend.y = y;
03086   _thd.next_drawstyle = b;
03087 }
03088 
03096 void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
03097 {
03098   int sx, sy;
03099   HighLightStyle style;
03100 
03101   if (x == -1) {
03102     _thd.selend.x = -1;
03103     return;
03104   }
03105 
03106   /* Special handling of drag in any (8-way) direction */
03107   if (method & (VPM_RAILDIRS | VPM_SIGNALDIRS)) {
03108     _thd.selend.x = x;
03109     _thd.selend.y = y;
03110     CalcRaildirsDrawstyle(x, y, method);
03111     return;
03112   }
03113 
03114   /* Needed so level-land is placed correctly */
03115   if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_POINT) {
03116     x += TILE_SIZE / 2;
03117     y += TILE_SIZE / 2;
03118   }
03119 
03120   sx = _thd.selstart.x;
03121   sy = _thd.selstart.y;
03122 
03123   int limit = 0;
03124 
03125   switch (method) {
03126     case VPM_X_OR_Y: // drag in X or Y direction
03127       if (abs(sy - y) < abs(sx - x)) {
03128         y = sy;
03129         style = HT_DIR_X;
03130       } else {
03131         x = sx;
03132         style = HT_DIR_Y;
03133       }
03134       goto calc_heightdiff_single_direction;
03135 
03136     case VPM_X_LIMITED: // Drag in X direction (limited size).
03137       limit = (_thd.sizelimit - 1) * TILE_SIZE;
03138       /* FALL THROUGH */
03139 
03140     case VPM_FIX_X: // drag in Y direction
03141       x = sx;
03142       style = HT_DIR_Y;
03143       goto calc_heightdiff_single_direction;
03144 
03145     case VPM_Y_LIMITED: // Drag in Y direction (limited size).
03146       limit = (_thd.sizelimit - 1) * TILE_SIZE;
03147       /* FALL THROUGH */
03148 
03149     case VPM_FIX_Y: // drag in X direction
03150       y = sy;
03151       style = HT_DIR_X;
03152 
03153 calc_heightdiff_single_direction:;
03154       if (limit > 0) {
03155         x = sx + Clamp(x - sx, -limit, limit);
03156         y = sy + Clamp(y - sy, -limit, limit);
03157       }
03158       if (_settings_client.gui.measure_tooltip) {
03159         TileIndex t0 = TileVirtXY(sx, sy);
03160         TileIndex t1 = TileVirtXY(x, y);
03161         uint distance = DistanceManhattan(t0, t1) + 1;
03162         byte index = 0;
03163         uint64 params[2];
03164 
03165         if (distance != 1) {
03166           /* With current code passing a HT_LINE style to calculate the height
03167            * difference is enough. However if/when a point-tool is created
03168            * with this method, function should be called with new_style (below)
03169            * instead of HT_LINE | style case HT_POINT is handled specially
03170            * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
03171           int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
03172 
03173           params[index++] = distance;
03174           if (heightdiff != 0) params[index++] = heightdiff;
03175         }
03176 
03177         ShowMeasurementTooltips(measure_strings_length[index], index, params);
03178       }
03179       break;
03180 
03181     case VPM_X_AND_Y_LIMITED: // Drag an X by Y constrained rect area.
03182       limit = (_thd.sizelimit - 1) * TILE_SIZE;
03183       x = sx + Clamp(x - sx, -limit, limit);
03184       y = sy + Clamp(y - sy, -limit, limit);
03185       /* FALL THROUGH */
03186 
03187     case VPM_X_AND_Y: // drag an X by Y area
03188       if (_settings_client.gui.measure_tooltip) {
03189         static const StringID measure_strings_area[] = {
03190           STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
03191         };
03192 
03193         TileIndex t0 = TileVirtXY(sx, sy);
03194         TileIndex t1 = TileVirtXY(x, y);
03195         uint dx = Delta(TileX(t0), TileX(t1)) + 1;
03196         uint dy = Delta(TileY(t0), TileY(t1)) + 1;
03197         byte index = 0;
03198         uint64 params[3];
03199 
03200         /* If dragging an area (eg dynamite tool) and it is actually a single
03201          * row/column, change the type to 'line' to get proper calculation for height */
03202         style = (HighLightStyle)_thd.next_drawstyle;
03203         if (_thd.IsDraggingDiagonal()) {
03204           /* Determine the "area" of the diagonal dragged selection.
03205            * We assume the area is the number of tiles along the X
03206            * edge and the number of tiles along the Y edge. However,
03207            * multiplying these two numbers does not give the exact
03208            * number of tiles; basically we are counting the black
03209            * squares on a chess board and ignore the white ones to
03210            * make the tile counts at the edges match up. There is no
03211            * other way to make a proper count though.
03212            *
03213            * First convert to the rotated coordinate system. */
03214           int dist_x = TileX(t0) - TileX(t1);
03215           int dist_y = TileY(t0) - TileY(t1);
03216           int a_max = dist_x + dist_y;
03217           int b_max = dist_y - dist_x;
03218 
03219           /* Now determine the size along the edge, but due to the
03220            * chess board principle this counts double. */
03221           a_max = abs(a_max + (a_max > 0 ? 2 : -2)) / 2;
03222           b_max = abs(b_max + (b_max > 0 ? 2 : -2)) / 2;
03223 
03224           /* We get a 1x1 on normal 2x1 rectangles, due to it being
03225            * a seen as two sides. As the result for actual building
03226            * will be the same as non-diagonal dragging revert to that
03227            * behaviour to give it a more normally looking size. */
03228           if (a_max != 1 || b_max != 1) {
03229             dx = a_max;
03230             dy = b_max;
03231           }
03232         } else if (style & HT_RECT) {
03233           if (dx == 1) {
03234             style = HT_LINE | HT_DIR_Y;
03235           } else if (dy == 1) {
03236             style = HT_LINE | HT_DIR_X;
03237           }
03238         }
03239 
03240         if (t0 != 1 || t1 != 1) {
03241           int heightdiff = CalcHeightdiff(style, 0, t0, t1);
03242 
03243           params[index++] = dx;
03244           params[index++] = dy;
03245           if (heightdiff != 0) params[index++] = heightdiff;
03246         }
03247 
03248         ShowMeasurementTooltips(measure_strings_area[index], index, params);
03249       }
03250       break;
03251 
03252     case VPM_A_B_LINE: { // drag an A to B line
03253       TileIndex t0 = TileVirtXY(sx, sy);
03254       TileIndex t1 = TileVirtXY(x, y);
03255       uint dx = Delta(TileX(t0), TileX(t1)) + 1;
03256       uint dy = Delta(TileY(t0), TileY(t1)) + 1;
03257       byte index = 0;
03258       uint64 params[5];
03259 
03260       /* If dragging an area (eg dynamite tool) and it is actually a single
03261        * row/column, change the type to 'line' to get proper calculation for height */
03262       style = (HighLightStyle)_thd.next_drawstyle;
03263       if (style & HT_RECT) {
03264         if (dx == 1) {
03265           style = HT_LINE | HT_DIR_Y;
03266         } else if (dy == 1) {
03267           style = HT_LINE | HT_DIR_X;
03268         }
03269       }
03270 
03271       if (dx != 1 || dy != 1) {
03272         int heightdiff = CalcHeightdiff(style, 0, t0, t1);
03273 
03274         params[index++] = DistanceManhattan(t0, t1);
03275         params[index++] = sqrtl(dx * dx + dy * dy); //DistanceSquare does not like big numbers
03276         params[index++] = DistanceFromEdge(t1);
03277         params[index++] = GetTileMaxZ(t1) / TILE_HEIGHT * TILE_HEIGHT_STEP;
03278         if (heightdiff != 0) params[index++] = heightdiff;
03279       }
03280       /* Show always the measurement tooltip */
03281       GuiShowTooltips(_thd.GetCallbackWnd(), STR_MEASURE_DIST_HEIGHTDIFF, index, params);
03282     break;
03283     }
03284 
03285     default: NOT_REACHED();
03286   }
03287 
03288   _thd.selend.x = x;
03289   _thd.selend.y = y;
03290 }
03291 
03296 EventState VpHandlePlaceSizingDrag()
03297 {
03298   if (_special_mouse_mode != WSM_SIZING) return ES_NOT_HANDLED;
03299 
03300   /* stop drag mode if the window has been closed */
03301   Window *w = _thd.GetCallbackWnd();
03302   if (w == NULL) {
03303     ResetObjectToPlace();
03304     return ES_HANDLED;
03305   }
03306 
03307   /* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
03308   if (_left_button_down) {
03309     w->OnPlaceDrag(_thd.select_method, _thd.select_proc, GetTileBelowCursor());
03310     return ES_HANDLED;
03311   }
03312 
03313   /* mouse button released..
03314    * keep the selected tool, but reset it to the original mode. */
03315   _special_mouse_mode = WSM_NONE;
03316   HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
03317   if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_RECT) {
03318     _thd.place_mode = HT_RECT | others;
03319   } else if (_thd.select_method & VPM_SIGNALDIRS) {
03320     _thd.place_mode = HT_RECT | others;
03321   } else if (_thd.select_method & VPM_RAILDIRS) {
03322     _thd.place_mode = (_thd.select_method & ~VPM_RAILDIRS) ? _thd.next_drawstyle : (HT_RAIL | others);
03323   } else {
03324     _thd.place_mode = HT_POINT | others;
03325   }
03326   SetTileSelectSize(1, 1);
03327 
03328   w->OnPlaceMouseUp(_thd.select_method, _thd.select_proc, _thd.selend, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y));
03329 
03330   return ES_HANDLED;
03331 }
03332 
03333 void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
03334 {
03335   SetObjectToPlace(icon, pal, mode, w->window_class, w->window_number);
03336 }
03337 
03338 #include "table/animcursors.h"
03339 
03340 void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
03341 {
03342   if (_thd.window_class != WC_INVALID) {
03343     /* Undo clicking on button and drag & drop */
03344     Window *w = _thd.GetCallbackWnd();
03345     /* Call the abort function, but set the window class to something
03346      * that will never be used to avoid infinite loops. Setting it to
03347      * the 'next' window class must not be done because recursion into
03348      * this function might in some cases reset the newly set object to
03349      * place or not properly reset the original selection. */
03350     _thd.window_class = WC_INVALID;
03351     if (w != NULL) w->OnPlaceObjectAbort();
03352   }
03353 
03354   SetTileSelectSize(1, 1);
03355 
03356   _thd.make_square_red = false;
03357 
03358   if (mode == HT_DRAG) { // HT_DRAG is for dragdropping trains in the depot window
03359     mode = HT_NONE;
03360     _special_mouse_mode = WSM_DRAGDROP;
03361   } else {
03362     _special_mouse_mode = WSM_NONE;
03363   }
03364 
03365   _thd.place_mode = mode;
03366   _thd.window_class = window_class;
03367   _thd.window_number = window_num;
03368 
03369   if ((mode & HT_DRAG_MASK) == HT_SPECIAL) { // special tools, like tunnels or docks start with presizing mode
03370     VpStartPreSizing();
03371   }
03372 
03373   if ((icon & ANIMCURSOR_FLAG) != 0) {
03374     SetAnimatedMouseCursor(_animcursors[icon & ~ANIMCURSOR_FLAG]);
03375   } else {
03376     SetMouseCursor(icon, pal);
03377   }
03378 
03379 }
03380 
03381 void ResetObjectToPlace()
03382 {
03383   SetObjectToPlace(SPR_CURSOR_MOUSE, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
03384 }