# 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 "waypoint_func.h"
    00045 #include "window_func.h"
    00046 #include "tilehighlight_func.h"
    00047 #include "window_gui.h"
    00048
    00049 #include "table/strings.h"
    00050
    00051 Point _tile_fract_coords;
    00052
    00053 struct StringSpriteToDraw {
    00054   StringID string;
    00055   Colours colour;
    00056   int32 x;
    00057   int32 y;
    00058   uint64 params[2];
    00059   uint16 width;
    00060 };
    00061
    00062 struct TileSpriteToDraw {
    00063   SpriteID image;
    00064   PaletteID pal;
    00065   const SubSprite *sub;
    00066   int32 x;
    00067   int32 y;
    00068 };
    00069
    00070 struct ChildScreenSpriteToDraw {
    00071   SpriteID image;
    00072   PaletteID pal;
    00073   const SubSprite *sub;
    00074   int32 x;
    00075   int32 y;
    00076   int next;
    00077 };
    00078
    00080 struct ParentSpriteToDraw {
    00081   SpriteID image;
    00082   PaletteID pal;
    00083   const SubSprite *sub;
    00084
    00085   int32 x;
    00086   int32 y;
    00087
    00088   int32 left;
    00089   int32 top;
    00090
    00091   int32 xmin;
    00092   int32 xmax;
    00093   int32 ymin;
    00094   int32 ymax;
    00095   int zmin;
    00096   int zmax;
    00097
    00098   int first_child;
    00099   bool comparison_done;
    00100 };
    00101
    00103 enum FoundationPart {
    00104   FOUNDATION_PART_NONE     = 0xFF,
    00105   FOUNDATION_PART_NORMAL   = 0,
    00106   FOUNDATION_PART_HALFTILE = 1,
    00107   FOUNDATION_PART_END
    00108 };
    00109
    00114 enum SpriteCombineMode {
    00115   SPRITE_COMBINE_NONE,
    00116   SPRITE_COMBINE_PENDING,
    00117   SPRITE_COMBINE_ACTIVE,
    00118 };
    00119
    00120 typedef SmallVector<TileSpriteToDraw, 64> TileSpriteToDrawVector;
    00121 typedef SmallVector<StringSpriteToDraw, 4> StringSpriteToDrawVector;
    00122 typedef SmallVector<ParentSpriteToDraw, 64> ParentSpriteToDrawVector;
    00123 typedef SmallVector<ParentSpriteToDraw*, 64> ParentSpriteToSortVector;
    00124 typedef SmallVector<ChildScreenSpriteToDraw, 16> ChildScreenSpriteToDrawVector;
    00125
    00127 struct ViewportDrawer {
    00128   DrawPixelInfo dpi;
    00129   const ViewPort *vp;
    00130   StringSpriteToDrawVector string_sprites_to_draw;
    00131   TileSpriteToDrawVector tile_sprites_to_draw;
    00132   ParentSpriteToDrawVector parent_sprites_to_draw;
    00133   ParentSpriteToSortVector parent_sprites_to_sort;
    00134   ChildScreenSpriteToDrawVector child_screen_sprites_to_draw;
    00135
    00136   int *last_child;
    00137
    00138   SpriteCombineMode combine_sprites;
    00139
    00140   int foundation[FOUNDATION_PART_END];
    00141   FoundationPart foundation_part;
    00142   int *last_foundation_child[FOUNDATION_PART_END];
    00143   Point foundation_offset[FOUNDATION_PART_END];
    00144 };
    00145
    00146 static ViewportDrawer _vd;
    00147
    00148 TileHighlightData _thd;
    00149 static TileInfo *_cur_ti;
    00150 bool _draw_bounding_boxes = false;
    00151
    00152 static Point MapXYZToViewport(const ViewPort *vp, int x, int y, int z)
    00153 {
    00154   Point p = RemapCoords(x, y, z);
    00155   p.x -= vp->virtual_width / 2;
    00156   p.y -= vp->virtual_height / 2;
    00157   return p;
    00158 }
    00159
    00160 void DeleteWindowViewport(Window *w)
    00161 {
    00162   free(w->viewport);
    00163   w->viewport = NULL;
    00164 }
    00165
    00178 void InitializeWindowViewport(Window *w, int x, int y,
    00179   int width, int height, uint32 follow_flags, ZoomLevel zoom)
    00180 {
    00181   assert(w->viewport == NULL);
    00182
    00183   ViewportData *vp = CallocT<ViewportData>(1);
    00184
    00185   vp->left = x + w->left;
    00186   vp->top = y + w->top;
    00187   vp->width = width;
    00188   vp->height = height;
    00189
    00190   vp->zoom = zoom;
    00191
    00192   vp->virtual_width = ScaleByZoom(width, zoom);
    00193   vp->virtual_height = ScaleByZoom(height, zoom);
    00194
    00195   Point pt;
    00196
    00197   if (follow_flags & 0x80000000) {
    00198     const Vehicle *veh;
    00199
    00200     vp->follow_vehicle = (VehicleID)(follow_flags & 0xFFFFF);
    00201     veh = Vehicle::Get(vp->follow_vehicle);
    00202     pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
    00203   } else {
    00204     uint x = TileX(follow_flags) * TILE_SIZE;
    00205     uint y = TileY(follow_flags) * TILE_SIZE;
    00206
    00207     vp->follow_vehicle = INVALID_VEHICLE;
    00208     pt = MapXYZToViewport(vp, x, y, GetSlopeZ(x, y));
    00209   }
    00210
    00211   vp->scrollpos_x = pt.x;
    00212   vp->scrollpos_y = pt.y;
    00213   vp->dest_scrollpos_x = pt.x;
    00214   vp->dest_scrollpos_y = pt.y;
    00215
    00216   w->viewport = vp;
    00217   vp->virtual_left = 0;//pt.x;
    00218   vp->virtual_top = 0;//pt.y;
    00219 }
    00220
    00221 static Point _vp_move_offs;
    00222
    00223 static void DoSetViewportPosition(const Window *w, int left, int top, int width, int height)
    00224 {
    00225   FOR_ALL_WINDOWS_FROM_BACK_FROM(w, w) {
    00226     if (left + width > w->left &&
    00227         w->left + w->width > left &&
    00228         top + height > w->top &&
    00229         w->top + w->height > top) {
    00230
    00231       if (left < w->left) {
    00232         DoSetViewportPosition(w, left, top, w->left - left, height);
    00233         DoSetViewportPosition(w, left + (w->left - left), top, width - (w->left - left), height);
    00234         return;
    00235       }
    00236
    00237       if (left + width > w->left + w->width) {
    00238         DoSetViewportPosition(w, left, top, (w->left + w->width - left), height);
    00239         DoSetViewportPosition(w, left + (w->left + w->width - left), top, width - (w->left + w->width - left), height);
    00240         return;
    00241       }
    00242
    00243       if (top < w->top) {
    00244         DoSetViewportPosition(w, left, top, width, (w->top - top));
    00245         DoSetViewportPosition(w, left, top + (w->top - top), width, height - (w->top - top));
    00246         return;
    00247       }
    00248
    00249       if (top + height > w->top + w->height) {
    00250         DoSetViewportPosition(w, left, top, width, (w->top + w->height - top));
    00251         DoSetViewportPosition(w, left, top + (w->top + w->height - top), width, height - (w->top + w->height - top));
    00252         return;
    00253       }
    00254
    00255       return;
    00256     }
    00257   }
    00258
    00259   {
    00260     int xo = _vp_move_offs.x;
    00261     int yo = _vp_move_offs.y;
    00262
    00263     if (abs(xo) >= width || abs(yo) >= height) {
    00264       /* fully_outside */
    00265       RedrawScreenRect(left, top, left + width, top + height);
    00266       return;
    00267     }
    00268
    00269     GfxScroll(left, top, width, height, xo, yo);
    00270
    00271     if (xo > 0) {
    00272       RedrawScreenRect(left, top, xo + left, top + height);
    00273       left += xo;
    00274       width -= xo;
    00275     } else if (xo < 0) {
    00276       RedrawScreenRect(left + width + xo, top, left + width, top + height);
    00277       width += xo;
    00278     }
    00279
    00280     if (yo > 0) {
    00281       RedrawScreenRect(left, top, width + left, top + yo);
    00282     } else if (yo < 0) {
    00283       RedrawScreenRect(left, top + height + yo, width + left, top + height);
    00284     }
    00285   }
    00286 }
    00287
    00288 static void SetViewportPosition(Window *w, int x, int y)
    00289 {
    00290   ViewPort *vp = w->viewport;
    00291   int old_left = vp->virtual_left;
    00292   int old_top = vp->virtual_top;
    00293   int i;
    00294   int left, top, width, height;
    00295
    00296
    00297   /* Viewport is bound to its left top corner, so it must be rounded down (UnScaleByZoomLower)
    00298    * else glitch described in FS#1412 will happen (offset by 1 pixel with zoom level > NORMAL)
    00299    */
    00300
    00301   x = UnScaleByZoom(x, vp->zoom);
    00302   y = UnScaleByZoom(y, vp->zoom);
    00303
    00304   vp->virtual_left = x;
    00305   vp->virtual_top  = y;
    00306
    00307   old_left -= x;
    00308   old_top -= y;
    00309
    00310   if (old_top == 0 && old_left == 0) return;
    00311
    00312   _vp_move_offs.x = old_left;
    00313   _vp_move_offs.y = old_top;
    00314
    00315   left = vp->left;
    00316   top = vp->top;
    00317   width = vp->width;
    00318   height = vp->height;
    00319
    00320   if (left < 0) {
    00321     width += left;
    00322     left = 0;
    00323   }
    00324
    00325   i = left + width - _screen.width;
    00326   if (i >= 0) width -= i;
    00327
    00328   if (width > 0) {
    00329     if (top < 0) {
    00330       height += top;
    00331       top = 0;
    00332     }
    00333
    00334     i = top + height - _screen.height;
    00335     if (i >= 0) height -= i;
    00336
    00337     if (height > 0) DoSetViewportPosition(w->z_front, left, top, width, height);
    00338   }
    00339 }
    00340
    00349 ViewPort *IsPtInWindowViewport(const Window *w, int x, int y)
    00350 {
    00351   ViewPort *vp = w->viewport;
    00352
    00353   if (vp != NULL &&
    00354       IsInsideMM(x, vp->left, vp->left + vp->width) &&
    00355       IsInsideMM(y, vp->top, vp->top + vp->height))
    00356     return vp;
    00357
    00358   return NULL;
    00359 }
    00360
    00368 static Point TranslateXYToTileCoord(const ViewPort *vp, int x, int y)
    00369 {
    00370   Point pt;
    00371   int a, b;
    00372   uint z;
    00373
    00374   if ( (uint)(x -= vp->left) >= (uint)vp->width ||
    00375         (uint)(y -= vp->top) >= (uint)vp->height) {
    00376         Point pt = {-1, -1};
    00377         return pt;
    00378   }
    00379
    00380   x = (ScaleByZoom(x + vp->virtual_left, vp->zoom) ) >> 2;
    00381   y = (ScaleByZoom(y + vp->virtual_top, vp->zoom) ) >> 1;
    00382   a = y - x;
    00383   b = y + x;
    00384
    00385   /* we need to move variables in to the valid range, as the
    00386    * GetTileZoomCenterWindow() function can call here with invalid x and/or y,
    00387    * when the user tries to zoom out along the sides of the map */
    00388   a = Clamp(a, -4 * (int)TILE_SIZE, (int)(MapMaxX() * TILE_SIZE) - 1);
    00389   b = Clamp(b, -4 * (int)TILE_SIZE, (int)(MapMaxY() * TILE_SIZE) - 1);
    00390
    00391   /* (a, b) is the X/Y-world coordinate that belongs to (x,y) if the landscape would be completely flat on height 0.
    00392    * Now find the Z-world coordinate by fix point iteration.
    00393    * This is a bit tricky because the tile height is non-continuous at foundations.
    00394    * The clicked point should be approached from the back, otherwise there are regions that are not clickable.
    00395    * (FOUNDATION_HALFTILE_LOWER on SLOPE_STEEP_S hides north halftile completely)
    00396    * So give it a z-malus of 4 in the first iterations.
    00397    */
    00398   z = 0;
    00399
    00400   int min_coord = _settings_game.construction.freeform_edges ? TILE_SIZE : 0;
    00401
    00402   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;
    00403   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;
    00404   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;
    00405
    00406   pt.x = Clamp(a + (int)z, min_coord, MapMaxX() * TILE_SIZE - 1);
    00407   pt.y = Clamp(b + (int)z, min_coord, MapMaxY() * TILE_SIZE - 1);
    00408
    00409   return pt;
    00410 }
    00411
    00412 /* When used for zooming, check area below current coordinates (x,y)
    00413  * and return the tile of the zoomed out/in position (zoom_x, zoom_y)
    00414  * when you just want the tile, make x = zoom_x and y = zoom_y */
    00415 static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
    00416 {
    00417   Window *w;
    00418   ViewPort *vp;
    00419   Point pt;
    00420
    00421   if ( (w = FindWindowFromPt(x, y)) != NULL &&
    00422        (vp = IsPtInWindowViewport(w, x, y)) != NULL)
    00423         return TranslateXYToTileCoord(vp, zoom_x, zoom_y);
    00424
    00425   pt.y = pt.x = -1;
    00426   return pt;
    00427 }
    00428
    00429 Point GetTileBelowCursor()
    00430 {
    00431   return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, _cursor.pos.x, _cursor.pos.y);
    00432 }
    00433
    00434
    00435 Point GetTileZoomCenterWindow(bool in, Window * w)
    00436 {
    00437   int x, y;
    00438   ViewPort *vp = w->viewport;
    00439
    00440   if (in) {
    00441     x = ((_cursor.pos.x - vp->left) >> 1) + (vp->width >> 2);
    00442     y = ((_cursor.pos.y - vp->top) >> 1) + (vp->height >> 2);
    00443   } else {
    00444     x = vp->width - (_cursor.pos.x - vp->left);
    00445     y = vp->height - (_cursor.pos.y - vp->top);
    00446   }
    00447   /* Get the tile below the cursor and center on the zoomed-out center */
    00448   return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, x + vp->left, y + vp->top);
    00449 }
    00450
    00459 void HandleZoomMessage(Window *w, const ViewPort *vp, byte widget_zoom_in, byte widget_zoom_out)
    00460 {
    00461   w->SetWidgetDisabledState(widget_zoom_in, vp->zoom == ZOOM_LVL_MIN);
    00462   w->SetWidgetDirty(widget_zoom_in);
    00463
    00464   w->SetWidgetDisabledState(widget_zoom_out, vp->zoom == ZOOM_LVL_MAX);
    00465   w->SetWidgetDirty(widget_zoom_out);
    00466 }
    00467
    00480 static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub = NULL, int extra_offs_x = 0, int extra_offs_y = 0)
    00481 {
    00482   assert((image & SPRITE_MASK) < MAX_SPRITES);
    00483
    00484   TileSpriteToDraw *ts = _vd.tile_sprites_to_draw.Append();
    00485   ts->image = image;
    00486   ts->pal = pal;
    00487   ts->sub = sub;
    00488   Point pt = RemapCoords(x, y, z);
    00489   ts->x = pt.x + extra_offs_x;
    00490   ts->y = pt.y + extra_offs_y;
    00491 }
    00492
    00505 static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
    00506 {
    00507   assert(IsInsideMM(foundation_part, 0, FOUNDATION_PART_END));
    00508   assert(_vd.foundation[foundation_part] != -1);
    00509   Point offs = _vd.foundation_offset[foundation_part];
    00510
    00511   /* Change the active ChildSprite list to the one of the foundation */
    00512   int *old_child = _vd.last_child;
    00513   _vd.last_child = _vd.last_foundation_child[foundation_part];
    00514
    00515   AddChildSpriteScreen(image, pal, offs.x + extra_offs_x, offs.y + extra_offs_y, false, sub);
    00516
    00517   /* Switch back to last ChildSprite list */
    00518   _vd.last_child = old_child;
    00519 }
    00520
    00534 void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
    00535 {
    00536   /* Switch to first foundation part, if no foundation was drawn */
    00537   if (_vd.foundation_part == FOUNDATION_PART_NONE) _vd.foundation_part = FOUNDATION_PART_NORMAL;
    00538
    00539   if (_vd.foundation[_vd.foundation_part] != -1) {
    00540     Point pt = RemapCoords(x, y, z);
    00541     AddChildSpriteToFoundation(image, pal, sub, _vd.foundation_part, pt.x + extra_offs_x, pt.y + extra_offs_y);
    00542   } else {
    00543     AddTileSpriteToDraw(image, pal, _cur_ti->x + x, _cur_ti->y + y, _cur_ti->z + z, sub, extra_offs_x, extra_offs_y);
    00544   }
    00545 }
    00546
    00557 void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
    00558 {
    00559   DrawGroundSpriteAt(image, pal, 0, 0, 0, sub, extra_offs_x, extra_offs_y);
    00560 }
    00561
    00569 void OffsetGroundSprite(int x, int y)
    00570 {
    00571   /* Switch to next foundation part */
    00572   switch (_vd.foundation_part) {
    00573     case FOUNDATION_PART_NONE:
    00574       _vd.foundation_part = FOUNDATION_PART_NORMAL;
    00575       break;
    00576     case FOUNDATION_PART_NORMAL:
    00577       _vd.foundation_part = FOUNDATION_PART_HALFTILE;
    00578       break;
    00579     default: NOT_REACHED();
    00580   }
    00581
    00582   /* _vd.last_child == NULL if foundation sprite was clipped by the viewport bounds */
    00583   if (_vd.last_child != NULL) _vd.foundation[_vd.foundation_part] = _vd.parent_sprites_to_draw.Length() - 1;
    00584
    00585   _vd.foundation_offset[_vd.foundation_part].x = x;
    00586   _vd.foundation_offset[_vd.foundation_part].y = y;
    00587   _vd.last_foundation_child[_vd.foundation_part] = _vd.last_child;
    00588 }
    00589
    00601 static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, byte z, const SubSprite *sub)
    00602 {
    00603   Point pt = RemapCoords(x, y, z);
    00604   const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
    00605
    00606   int xu = UnScaleByZoom(pt.x, _vd.dpi.zoom);
    00607   int yu = UnScaleByZoom(pt.y, _vd.dpi.zoom);
    00608
    00609   if (xu + spr->x_offs >= _vd.vp->virtual_left + _vd.vp->width ||
    00610      xu + spr->x_offs + spr->width <= _vd.vp->virtual_left ||
    00611      yu + spr->y_offs >= _vd.vp->virtual_top + _vd.vp->height ||
    00612      yu + spr->y_offs + spr->height <= _vd.vp->virtual_top)
    00613     return;
    00614
    00615   const ParentSpriteToDraw *pstd = _vd.parent_sprites_to_draw.End() - 1;
    00616   AddChildSpriteScreen(image, pal, pt.x - pstd->left, pt.y - pstd->top, false, sub);
    00617 }
    00618
    00644 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)
    00645 {
    00646   int32 left, right, top, bottom;
    00647
    00648   assert((image & SPRITE_MASK) < MAX_SPRITES);
    00649
    00650   /* make the sprites transparent with the right palette */
    00651   if (transparent) {
    00652     SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
    00653   }
    00654
    00655   if (_vd.combine_sprites == SPRITE_COMBINE_ACTIVE) {
    00656     AddCombinedSprite(image, pal, x, y, z, sub);
    00657     return;
    00658   }
    00659
    00660   _vd.last_child = NULL;
    00661
    00662   Point pt = RemapCoords(x, y, z);
    00663   int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
    00664
    00665   /* Compute screen extents of sprite */
    00666   if (image == SPR_EMPTY_BOUNDING_BOX) {
    00667     left = tmp_left = RemapCoords(x + w          , y + bb_offset_y, z + bb_offset_z).x;
    00668     right           = RemapCoords(x + bb_offset_x, y + h          , z + bb_offset_z).x + 1;
    00669     top  = tmp_top  = RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz         ).y;
    00670     bottom          = RemapCoords(x + w          , y + h          , z + bb_offset_z).y + 1;
    00671   } else {
    00672     const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
    00673     int x_offs, y_offs,swidth, sheight;
    00674
    00675     x_offs = ScaleByZoom(spr->x_offs, _vd.vp->zoom);
    00676     y_offs = ScaleByZoom(spr->y_offs, _vd.vp->zoom);
    00677     swidth = ScaleByZoom(spr->width, _vd.vp->zoom);
    00678     sheight = ScaleByZoom(spr->height, _vd.vp->zoom);
    00679     left = tmp_left = (pt.x += x_offs);
    00680     right = (pt.x +  swidth );
    00681     top  = tmp_top  = (pt.y += y_offs);
    00682     bottom = (pt.y +  sheight);
    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 (UnScaleByZoom(left, _vd.vp->zoom)    >= _vd.vp->virtual_left + _vd.vp->width ||
    00695      UnScaleByZoom(right, _vd.vp->zoom)  <= _vd.vp->virtual_left ||
    00696      UnScaleByZoom(top, _vd.vp->zoom)    >= _vd.vp->virtual_top + _vd.vp->height  ||
    00697      UnScaleByZoom(bottom, _vd.vp->zoom) <= _vd.vp->virtual_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   }
    00815
    00816   *_vd.last_child = _vd.child_screen_sprites_to_draw.Length();
    00817
    00818   ChildScreenSpriteToDraw *cs = _vd.child_screen_sprites_to_draw.Append();
    00819   cs->image = image;
    00820   cs->pal = pal;
    00821   cs->sub = sub;
    00822   cs->x = UnScaleByZoom(x, _vd.dpi.zoom);
    00823   cs->y = UnScaleByZoom(y, _vd.dpi.zoom);
    00824   cs->next = -1;
    00825
    00826   /* Append the sprite to the active ChildSprite list.
    00827    * If the active ParentSprite is a foundation, update last_foundation_child as well.
    00828    * Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
    00829   if (_vd.last_foundation_child[0] == _vd.last_child) _vd.last_foundation_child[0] = &cs->next;
    00830   if (_vd.last_foundation_child[1] == _vd.last_child) _vd.last_foundation_child[1] = &cs->next;
    00831   _vd.last_child = &cs->next;
    00832 }
    00833
    00834 static void AddStringToDraw(int x, int y, StringID string, uint64 params_1, uint64 params_2, Colours colour, uint16 width)
    00835 {
    00836   assert(width != 0);
    00837   StringSpriteToDraw *ss = _vd.string_sprites_to_draw.Append();
    00838   ss->string = string;
    00839   ss->x = x;
    00840   ss->y = y;
    00841   ss->params[0] = params_1;
    00842   ss->params[1] = params_2;
    00843   ss->width = width;
    00844   ss->colour = colour;
    00845 }
    00846
    00847
    00859 static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part)
    00860 {
    00861   /* FIXME: This is not totally valid for some autorail highlights that extend over the edges of the tile. */
    00862   if (_vd.foundation[foundation_part] == -1) {
    00863     /* draw on real ground */
    00864     AddTileSpriteToDraw(image, pal, ti->x, ti->y, ti->z + z_offset);
    00865   } else {
    00866     /* draw on top of foundation */
    00867     AddChildSpriteToFoundation(image, pal, NULL, foundation_part, 0, -z_offset);
    00868   }
    00869 }
    00870
    00877 static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
    00878 {
    00879   if (!IsValidTile(ti->tile)) return;
    00880
    00881   SpriteID sel;
    00882   if (IsHalftileSlope(ti->tileh)) {
    00883     Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
    00884     SpriteID sel2 = SPR_HALFTILE_SELECTION_FLAT + halftile_corner;
    00885     DrawSelectionSprite(sel2, pal, ti, 7 + TILE_HEIGHT, FOUNDATION_PART_HALFTILE);
    00886
    00887     Corner opposite_corner = OppositeCorner(halftile_corner);
    00888     if (IsSteepSlope(ti->tileh)) {
    00889       sel = SPR_HALFTILE_SELECTION_DOWN;
    00890     } else {
    00891       sel = ((ti->tileh & SlopeWithOneCornerRaised(opposite_corner)) != 0 ? SPR_HALFTILE_SELECTION_UP : SPR_HALFTILE_SELECTION_FLAT);
    00892     }
    00893     sel += opposite_corner;
    00894   } else {
    00895     sel = SPR_SELECT_TILE + SlopeToSpriteOffset(ti->tileh);
    00896   }
    00897   DrawSelectionSprite(sel, pal, ti, 7, FOUNDATION_PART_NORMAL);
    00898 }
    00899
    00900 static bool IsPartOfAutoLine(int px, int py)
    00901 {
    00902   px -= _thd.selstart.x;
    00903   py -= _thd.selstart.y;
    00904
    00905   if ((_thd.drawstyle & HT_DRAG_MASK) != HT_LINE) return false;
    00906
    00907   switch (_thd.drawstyle & HT_DIR_MASK) {
    00908     case HT_DIR_X:  return py == 0; // x direction
    00909     case HT_DIR_Y:  return px == 0; // y direction
    00910     case HT_DIR_HU: return px == -py || px == -py - 16; // horizontal upper
    00911     case HT_DIR_HL: return px == -py || px == -py + 16; // horizontal lower
    00912     case HT_DIR_VL: return px == py || px == py + 16; // vertical left
    00913     case HT_DIR_VR: return px == py || px == py - 16; // vertical right
    00914     default:
    00915       NOT_REACHED();
    00916   }
    00917 }
    00918
    00919 /* [direction][side] */
    00920 static const HighLightStyle _autorail_type[6][2] = {
    00921   { HT_DIR_X,  HT_DIR_X },
    00922   { HT_DIR_Y,  HT_DIR_Y },
    00923   { HT_DIR_HU, HT_DIR_HL },
    00924   { HT_DIR_HL, HT_DIR_HU },
    00925   { HT_DIR_VL, HT_DIR_VR },
    00926   { HT_DIR_VR, HT_DIR_VL }
    00927 };
    00928
    00929 #include "table/autorail.h"
    00930
    00937 static void DrawAutorailSelection(const TileInfo *ti, uint autorail_type)
    00938 {
    00939   SpriteID image;
    00940   PaletteID pal;
    00941   int offset;
    00942
    00943   FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
    00944   Slope autorail_tileh = RemoveHalftileSlope(ti->tileh);
    00945   if (IsHalftileSlope(ti->tileh)) {
    00946     static const uint _lower_rail[4] = { 5U, 2U, 4U, 3U };
    00947     Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
    00948     if (autorail_type != _lower_rail[halftile_corner]) {
    00949       foundation_part = FOUNDATION_PART_HALFTILE;
    00950       /* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
    00951       autorail_tileh = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
    00952     }
    00953   }
    00954
    00955   offset = _AutorailTilehSprite[autorail_tileh][autorail_type];
    00956   if (offset >= 0) {
    00957     image = SPR_AUTORAIL_BASE + offset;
    00958     pal = PAL_NONE;
    00959   } else {
    00960     image = SPR_AUTORAIL_BASE - offset;
    00961     pal = PALETTE_SEL_TILE_RED;
    00962   }
    00963
    00964   DrawSelectionSprite(image, _thd.make_square_red ? PALETTE_SEL_TILE_RED : pal, ti, 7, foundation_part);
    00965 }
    00966
    00971 static void DrawTileSelection(const TileInfo *ti)
    00972 {
    00973   /* Draw a red error square? */
    00974   bool is_redsq = _thd.redsq == ti->tile;
    00975   if (is_redsq) DrawTileSelectionRect(ti, PALETTE_TILE_RED_PULSATING);
    00976
    00977   /* No tile selection active? */
    00978   if ((_thd.drawstyle & HT_DRAG_MASK) == HT_NONE) return;
    00979
    00980   if (_thd.diagonal) { // We're drawing a 45 degrees rotated (diagonal) rectangle
    00981     if (IsInsideRotatedRectangle((int)ti->x, (int)ti->y)) goto draw_inner;
    00982     return;
    00983   }
    00984
    00985   /* Inside the inner area? */
    00986   if (IsInsideBS(ti->x, _thd.pos.x, _thd.size.x) &&
    00987       IsInsideBS(ti->y, _thd.pos.y, _thd.size.y)) {
    00988 draw_inner:
    00989     if (_thd.drawstyle & HT_RECT) {
    00990       if (!is_redsq) DrawTileSelectionRect(ti, _thd.make_square_red ? PALETTE_SEL_TILE_RED : PAL_NONE);
    00991     } else if (_thd.drawstyle & HT_POINT) {
    00992       /* Figure out the Z coordinate for the single dot. */
    00993       byte z = 0;
    00994       FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
    00995       if (ti->tileh & SLOPE_N) {
    00996         z += TILE_HEIGHT;
    00997         if (RemoveHalftileSlope(ti->tileh) == SLOPE_STEEP_N) z += TILE_HEIGHT;
    00998       }
    00999       if (IsHalftileSlope(ti->tileh)) {
    01000         Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
    01001         if ((halftile_corner == CORNER_W) || (halftile_corner == CORNER_E)) z += TILE_HEIGHT;
    01002         if (halftile_corner != CORNER_S) {
    01003           foundation_part = FOUNDATION_PART_HALFTILE;
    01004           if (IsSteepSlope(ti->tileh)) z -= TILE_HEIGHT;
    01005         }
    01006       }
    01007       DrawSelectionSprite(_cur_dpi->zoom <= ZOOM_LVL_DETAIL ? SPR_DOT : SPR_DOT_SMALL, PAL_NONE, ti, z, foundation_part);
    01008     } else if (_thd.drawstyle & HT_RAIL) {
    01009       /* autorail highlight piece under cursor */
    01010       HighLightStyle type = _thd.drawstyle & HT_DIR_MASK;
    01011       assert(type < HT_DIR_END);
    01012       DrawAutorailSelection(ti, _autorail_type[type][0]);
    01013     } else if (IsPartOfAutoLine(ti->x, ti->y)) {
    01014       /* autorail highlighting long line */
    01015       HighLightStyle dir = _thd.drawstyle & HT_DIR_MASK;
    01016       uint side;
    01017
    01018       if (dir == HT_DIR_X || dir == HT_DIR_Y) {
    01019         side = 0;
    01020       } else {
    01021         TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
    01022         side = Delta(Delta(TileX(start), TileX(ti->tile)), Delta(TileY(start), TileY(ti->tile)));
    01023       }
    01024
    01025       DrawAutorailSelection(ti, _autorail_type[dir][side]);
    01026     }
    01027     return;
    01028   }
    01029
    01030   /* Check if it's inside the outer area? */
    01031   if (!is_redsq && _thd.outersize.x > 0 &&
    01032       IsInsideBS(ti->x, _thd.pos.x + _thd.offs.x, _thd.size.x + _thd.outersize.x) &&
    01033       IsInsideBS(ti->y, _thd.pos.y + _thd.offs.y, _thd.size.y + _thd.outersize.y)) {
    01034     /* Draw a blue rect. */
    01035     DrawTileSelectionRect(ti, PALETTE_SEL_TILE_BLUE);
    01036     return;
    01037   }
    01038 }
    01039
    01040 static void ViewportAddLandscape()
    01041 {
    01042   int x, y, x1, y1, width, nof_sprites_drawn;
    01043   int top, bottom;
    01044   TileInfo ti;
    01045   bool direction;
    01046   Point pt;
    01047
    01048   _cur_ti = &ti;
    01049
    01050   x1 = ScaleByZoomLower(_vd.vp->virtual_left + _vd.dpi.left, _vd.vp->zoom)  ;
    01051   y1 = ScaleByZoomLower(_vd.vp->virtual_top + _vd.dpi.top, _vd.vp->zoom)  ;
    01052
    01053   x1 = x1 / 4;
    01054   y1 = y1 / 2;
    01055
    01056   x = ((y1 - x1) / TILE_SIZE) * TILE_SIZE ;
    01057   y = ((y1 + x1) / TILE_SIZE) * TILE_SIZE - (TILE_SIZE << 1);
    01058
    01059   width  = (_vd.dpi.width / UnScaleByZoom(64, _vd.vp->zoom)) + 4;
    01060
    01061   bottom = ScaleByZoom(_vd.vp->virtual_top + _vd.dpi.top + _vd.dpi.height, _vd.vp->zoom) + 128;
    01062   top = ScaleByZoom(_vd.vp->virtual_top + _vd.dpi.top, _vd.vp->zoom) ;
    01063   assert(width > 0);
    01064
    01065   direction = false;
    01066
    01067   do {
    01068     int width_cur = width;
    01069     uint x_cur = x;
    01070     uint y_cur = y;
    01071     nof_sprites_drawn = 0;
    01072     do {
    01073       TileType tt = MP_VOID;
    01074
    01075       ti.x = x_cur;
    01076       ti.y = y_cur;
    01077
    01078       ti.z = 0;
    01079
    01080       ti.tileh = SLOPE_FLAT;
    01081       ti.tile = INVALID_TILE;
    01082
    01083       if (x_cur < MapMaxX() * TILE_SIZE &&
    01084           y_cur < MapMaxY() * TILE_SIZE) {
    01085         TileIndex tile = TileVirtXY(x_cur, y_cur);
    01086
    01087         if (!_settings_game.construction.freeform_edges || (TileX(tile) != 0 && TileY(tile) != 0)) {
    01088           if (x_cur == ((int)MapMaxX() - 1) * TILE_SIZE || y_cur == ((int)MapMaxY() - 1) * TILE_SIZE) {
    01089             uint maxh = max<uint>(TileHeight(tile), 1);
    01090             for (uint h = 0; h < maxh; h++) {
    01091               AddTileSpriteToDraw(SPR_SHADOW_CELL, PAL_NONE, ti.x, ti.y, h * TILE_HEIGHT);
    01092             }
    01093           }
    01094
    01095           ti.tile = tile;
    01096           ti.tileh = GetTileSlope(tile, &ti.z);
    01097           tt = GetTileType(tile);
    01098         }
    01099       }
    01100       pt = RemapCoords(ti.x,ti.y,ti.z);
    01101       if (pt.y < bottom) {
    01102         _vd.foundation_part = FOUNDATION_PART_NONE;
    01103         _vd.foundation[0] = -1;
    01104         _vd.foundation[1] = -1;
    01105         _vd.last_foundation_child[0] = NULL;
    01106         _vd.last_foundation_child[1] = NULL;
    01107         _tile_type_procs[tt]->draw_tile_proc(&ti);
    01108         if (ti.tile != INVALID_TILE) DrawTileSelection(&ti);
    01109         nof_sprites_drawn++;
    01110       }
    01111       y_cur += 0x10;
    01112       x_cur -= 0x10;
    01113     } while (--width_cur);
    01114
    01115     if ((direction ^= 1) != 0) {
    01116       y += 0x10;
    01117     } else {
    01118       x += 0x10;
    01119     }
    01120   } while (nof_sprites_drawn || (pt.y < top));
    01121 }
    01122
    01133 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)
    01134 {
    01135   bool small = dpi->zoom >= small_from;
    01136
    01137   int left   = dpi->left;
    01138   int top    = dpi->top;
    01139   int right  = left + dpi->width;
    01140   int bottom = top + dpi->height;
    01141
    01142   int sign_height     = ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM, dpi->zoom);
    01143   int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, dpi->zoom);
    01144
    01145
    01146   left = ScaleByZoom(_vd.vp->virtual_left  + dpi->left, dpi->zoom);
    01147   top =  ScaleByZoom(_vd.vp->virtual_top  + dpi->top, dpi->zoom);
    01148   right = left + ScaleByZoom(dpi->width, dpi->zoom);
    01149   bottom = top + ScaleByZoom(dpi->height, dpi->zoom);
    01150
    01151
    01152   if (bottom < sign->top ||
    01153       top   > sign->top + sign_height ||
    01154       right < sign->center - sign_half_width ||
    01155       left  > sign->center + sign_half_width) {
    01156     return;
    01157   }
    01158
    01159   if (!small) {
    01160     AddStringToDraw(sign->center - sign_half_width, sign->top, string_normal, params_1, params_2, colour, sign->width_normal);
    01161   } else {
    01162     int shadow_offset = 0;
    01163     if (string_small_shadow != STR_NULL) {
    01164       shadow_offset = 4;
    01165       AddStringToDraw(sign->center - sign_half_width + shadow_offset, sign->top, string_small_shadow, params_1, params_2, INVALID_COLOUR, sign->width_small);
    01166     }
    01167     AddStringToDraw(sign->center - sign_half_width, sign->top - shadow_offset, string_small, params_1, params_2,
    01168         colour, sign->width_small | 0x8000);
    01169   }
    01170 }
    01171
    01172 static void ViewportAddTownNames(DrawPixelInfo *dpi)
    01173 {
    01174   if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES) || _game_mode == GM_MENU) return;
    01175
    01176   const Town *t;
    01177   FOR_ALL_TOWNS(t) {
    01178     ViewportAddString(dpi, ZOOM_LVL_OUT_4X, &t->sign,
    01179         _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
    01180         STR_VIEWPORT_TOWN_TINY_WHITE, STR_VIEWPORT_TOWN_TINY_BLACK,
    01181         t->index, t->population);
    01182   }
    01183 }
    01184
    01185
    01186 static void ViewportAddStationNames(DrawPixelInfo *dpi)
    01187 {
    01188   if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || _game_mode == GM_MENU) return;
    01189
    01190   const BaseStation *st;
    01191   FOR_ALL_BASE_STATIONS(st) {
    01192     /* Check whether the base station is a station or a waypoint */
    01193     bool is_station = Station::IsExpected(st);
    01194
    01195     /* Don't draw if the display options are disabled */
    01196     if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
    01197
    01198     ViewportAddString(dpi, ZOOM_LVL_OUT_4X, &st->sign,
    01199         is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT,
    01200         (is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT) + 1, STR_NULL,
    01201         st->index, st->facilities, (st->owner == OWNER_NONE || !st->IsInUse()) ? COLOUR_GREY : _company_colours[st->owner]);
    01202   }
    01203 }
    01204
    01205
    01206 static void ViewportAddSigns(DrawPixelInfo *dpi)
    01207 {
    01208   /* Signs are turned off or are invisible */
    01209   if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS)) return;
    01210
    01211   const Sign *si;
    01212   FOR_ALL_SIGNS(si) {
    01213     ViewportAddString(dpi, ZOOM_LVL_OUT_4X, &si->sign,
    01214         STR_WHITE_SIGN,
    01215         IsTransparencySet(TO_SIGNS) ? STR_VIEWPORT_SIGN_SMALL_WHITE : STR_VIEWPORT_SIGN_SMALL_BLACK, STR_NULL,
    01216         si->index, 0, (si->owner == OWNER_NONE) ? COLOUR_GREY : _company_colours[si->owner]);
    01217   }
    01218 }
    01219
    01226 void ViewportSign::UpdatePosition(int center, int top, StringID str)
    01227 {
    01228   if (this->width_normal != 0) this->MarkDirty();
    01229
    01230   this->top = top;
    01231
    01232   char buffer[DRAW_STRING_BUFFER];
    01233
    01234   GetString(buffer, str, lastof(buffer));
    01235   this->width_normal = VPSM_LEFT + Align(GetStringBoundingBox(buffer).width, 2) + VPSM_RIGHT;
    01236   this->center = center;
    01237
    01238   /* zoomed out version */
    01239   this->width_small = VPSM_LEFT + Align(GetStringBoundingBox(buffer, FS_SMALL).width, 2) + VPSM_RIGHT;
    01240
    01241   this->MarkDirty();
    01242 }
    01243
    01249 void ViewportSign::MarkDirty() const
    01250 {
    01251   /* We use ZOOM_LVL_MAX here, as every viewport can have another zoom,
    01252    *  and there is no way for us to know which is the biggest. So make the
    01253    *  biggest area dirty, and we are safe for sure.
    01254    * We also add 1 to make sure the whole thing is redrawn. */
    01255   MarkAllViewportsDirty(
    01256     this->center - ScaleByZoom(this->width_normal / 2 + 1, ZOOM_LVL_MAX),
    01257     this->top    - ScaleByZoom(1, ZOOM_LVL_MAX),
    01258     this->center + ScaleByZoom(this->width_normal / 2 + 1, ZOOM_LVL_MAX),
    01259     this->top    + ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM + 1, ZOOM_LVL_MAX));
    01260 }
    01261
    01262 static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
    01263 {
    01264   const TileSpriteToDraw *tsend = tstdv->End();
    01265   for (const TileSpriteToDraw *ts = tstdv->Begin(); ts != tsend; ++ts) {
    01266     int left = UnScaleByZoom(ts->x,_vd.vp->zoom);
    01267     int top =  UnScaleByZoom(ts->y,_vd.vp->zoom);
    01268
    01269
    01270     left -= _vd.vp->virtual_left;
    01271     top  -= _vd.vp->virtual_top;
    01272
    01273     DrawSprite(ts->image, ts->pal, left, top, ts->sub);
    01274   }
    01275 }
    01276
    01278 static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
    01279 {
    01280   ParentSpriteToDraw **psdvend = psdv->End();
    01281   ParentSpriteToDraw **psd = psdv->Begin();
    01282   while (psd != psdvend) {
    01283     ParentSpriteToDraw *ps = *psd;
    01284
    01285     if (ps->comparison_done) {
    01286       psd++;
    01287       continue;
    01288     }
    01289
    01290     ps->comparison_done = true;
    01291
    01292     for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) {
    01293       ParentSpriteToDraw *ps2 = *psd2;
    01294
    01295       if (ps2->comparison_done) continue;
    01296
    01297       /* Decide which comparator to use, based on whether the bounding
    01298        * boxes overlap
    01299        */
    01300       if (ps->xmax >= ps2->xmin && ps->xmin <= ps2->xmax && // overlap in X?
    01301           ps->ymax >= ps2->ymin && ps->ymin <= ps2->ymax && // overlap in Y?
    01302           ps->zmax >= ps2->zmin && ps->zmin <= ps2->zmax) { // overlap in Z?
    01303         /* Use X+Y+Z as the sorting order, so sprites closer to the bottom of
    01304          * the screen and with higher Z elevation, are drawn in front.
    01305          * Here X,Y,Z are the coordinates of the "center of mass" of the sprite,
    01306          * i.e. X=(left+right)/2, etc.
    01307          * However, since we only care about order, don't actually divide / 2
    01308          */
    01309         if (ps->xmin + ps->xmax + ps->ymin + ps->ymax + ps->zmin + ps->zmax <=
    01310             ps2->xmin + ps2->xmax + ps2->ymin + ps2->ymax + ps2->zmin + ps2->zmax) {
    01311           continue;
    01312         }
    01313       } else {
    01314         /* We only change the order, if it is definite.
    01315          * I.e. every single order of X, Y, Z says ps2 is behind ps or they overlap.
    01316          * That is: If one partial order says ps behind ps2, do not change the order.
    01317          */
    01318         if (ps->xmax < ps2->xmin ||
    01319             ps->ymax < ps2->ymin ||
    01320             ps->zmax < ps2->zmin) {
    01321           continue;
    01322         }
    01323       }
    01324
    01325       /* Move ps2 in front of ps */
    01326       ParentSpriteToDraw *temp = ps2;
    01327       for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) {
    01328         *psd3 = *(psd3 - 1);
    01329       }
    01330       *psd = temp;
    01331     }
    01332   }
    01333 }
    01334
    01335 static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
    01336 {
    01337   int  x,y, left, top;
    01338   const ParentSpriteToDraw * const *psd_end = psd->End();
    01339   for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
    01340     const ParentSpriteToDraw* ps = *it;
    01341
    01342     x = UnScaleByZoom(ps->x, _cur_dpi->zoom) - _vd.vp->virtual_left;
    01343     y = UnScaleByZoom(ps->y, _cur_dpi->zoom) - _vd.vp->virtual_top;
    01344     left = UnScaleByZoom(ps->left, _cur_dpi->zoom) - _vd.vp->virtual_left;
    01345     top = UnScaleByZoom(ps->top, _cur_dpi->zoom) - _vd.vp->virtual_top;
    01346     if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSprite(ps->image, ps->pal, x, y, ps->sub);
    01347
    01348     int child_idx = ps->first_child;
    01349     while (child_idx >= 0) {
    01350       const ChildScreenSpriteToDraw *cs = csstdv->Get(child_idx);
    01351       child_idx = cs->next;
    01352       DrawSprite(cs->image, cs->pal, left + cs->x, top + cs->y, cs->sub);
    01353     }
    01354   }
    01355 }
    01356
    01361 static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
    01362 {
    01363   ZoomLevel zoom = _cur_dpi->zoom;
    01364
    01365   const ParentSpriteToDraw * const *psd_end = psd->End();
    01366   for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
    01367     const ParentSpriteToDraw *ps = *it;
    01368
    01369     Point pt1 = RemapCoords(ps->xmax, ps->ymax, ps->zmax); // top front corner
    01370     Point pt2 = RemapCoords(ps->xmin, ps->ymax, ps->zmax); // top left corner
    01371     Point pt3 = RemapCoords(ps->xmax, ps->ymin, ps->zmax); // top right corner
    01372     Point pt4 = RemapCoords(ps->xmax, ps->ymax, ps->zmin); // bottom front corner
    01373
    01374
    01375     pt1.x = UnScaleByZoom(pt1.x, zoom) - _vd.vp->virtual_left;
    01376     pt1.y = UnScaleByZoom(pt1.y, zoom) - _vd.vp->virtual_top;
    01377     pt2.x = UnScaleByZoom(pt2.x, zoom) - _vd.vp->virtual_left;
    01378     pt2.y = UnScaleByZoom(pt2.y, zoom) - _vd.vp->virtual_top;
    01379     pt3.x = UnScaleByZoom(pt3.x, zoom) - _vd.vp->virtual_left;
    01380     pt3.y = UnScaleByZoom(pt3.y, zoom) - _vd.vp->virtual_top;
    01381     pt4.x = UnScaleByZoom(pt4.x, zoom) - _vd.vp->virtual_left;
    01382     pt4.y = UnScaleByZoom(pt4.y, zoom) - _vd.vp->virtual_top;
    01383
    01384
    01385     DrawBox(        pt1.x,         pt1.y,
    01386             pt2.x - pt1.x, pt2.y - pt1.y,
    01387             pt3.x - pt1.x, pt3.y - pt1.y,
    01388             pt4.x - pt1.x, pt4.y - pt1.y);
    01389   }
    01390 }
    01391
    01392 static void ViewportDrawStrings(DrawPixelInfo *dpi, const StringSpriteToDrawVector *sstdv)
    01393 {
    01394   DrawPixelInfo dp;
    01395   ZoomLevel zoom;
    01396
    01397   _cur_dpi = &dp;
    01398   dp = *dpi;
    01399
    01400   zoom = dp.zoom;
    01401   zoom = _vd.vp->zoom;
    01402   dp.zoom = ZOOM_LVL_NORMAL;
    01403
    01404   const StringSpriteToDraw *ssend = sstdv->End();
    01405   for (const StringSpriteToDraw *ss = sstdv->Begin(); ss != ssend; ++ss) {
    01406     TextColour colour = TC_BLACK;
    01407     bool small = HasBit(ss->width, 15);
    01408     int w = GB(ss->width, 0, 15);
    01409
    01410     int x = UnScaleByZoom(ss->x, zoom) - _vd.vp->virtual_left;
    01411     int y = UnScaleByZoom(ss->y, zoom) - _vd.vp->virtual_top;
    01412     int h = VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM;
    01413
    01414     SetDParam(0, ss->params[0]);
    01415     SetDParam(1, ss->params[1]);
    01416
    01417     if (ss->colour != INVALID_COLOUR) {
    01418       /* Do not draw signs nor station names if they are set invisible */
    01419       if (IsInvisibilitySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) continue;
    01420
    01421       /* if we didn't draw a rectangle, or if transparant building is on,
    01422        * draw the text in the colour the rectangle would have */
    01423       if (IsTransparencySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) {
    01424         /* Real colours need the TC_IS_PALETTE_COLOUR flag
    01425          * otherwise colours from _string_colourmap are assumed. */
    01426         colour = (TextColour)_colour_gradient[ss->colour][6] | TC_IS_PALETTE_COLOUR;
    01427       }
    01428
    01429       /* Draw the rectangle if 'tranparent station signs' is off,
    01430        * or if we are drawing a general text sign (STR_WHITE_SIGN) */
    01431       if (!IsTransparencySet(TO_SIGNS) || ss->string == STR_WHITE_SIGN) {
    01432         DrawFrameRect(
    01433           x, y, x + w, y + h, ss->colour,
    01434           IsTransparencySet(TO_SIGNS) ? FR_TRANSPARENT : FR_NONE
    01435         );
    01436       }
    01437     }
    01438     DrawString(x + VPSM_LEFT, x + w - 1 - VPSM_RIGHT, y + VPSM_TOP, ss->string, colour, SA_HOR_CENTER);
    01439   }
    01440 }
    01441
    01442 void ViewportDoDraw(const ViewPort *vp, int left, int top, int right, int bottom)
    01443 {
    01444   DrawPixelInfo *old_dpi = _cur_dpi;
    01445   DrawPixelInfo tmp_dpi;
    01446
    01447   _cur_dpi = &_vd.dpi;
    01448   _cur_dpi->zoom = vp->zoom;
    01449
    01450
    01451   int x = left;
    01452   int y = top;
    01453
    01454   left = left - vp->left;
    01455   top  = top - vp->top;
    01456   right = right - vp->left;
    01457   bottom = bottom - vp->top;
    01458
    01459   _vd.dpi.zoom = vp->zoom;
    01460   _vd.combine_sprites = SPRITE_COMBINE_NONE;
    01461   _vd.dpi.width = (right - left) ;
    01462   _vd.dpi.height = (bottom - top) ;
    01463   _vd.dpi.left = left ;
    01464   _vd.dpi.top = top ;
    01465   _vd.dpi.pitch = old_dpi->pitch;
    01466   _vd.last_child = NULL;
    01467   _vd.vp = vp;
    01468   _vd.dpi.dst_ptr = BlitterFactoryBase::GetCurrentBlitter()->MoveTo(old_dpi->dst_ptr, x - old_dpi->left, y - old_dpi->top);
    01469
    01470   ViewportAddLandscape();
    01471
    01472   tmp_dpi = _vd.dpi;
    01473   tmp_dpi.left = ScaleByZoom(vp->virtual_left, vp->zoom);
    01474   tmp_dpi.top = ScaleByZoom(vp->virtual_top, vp->zoom);
    01475   tmp_dpi.width = ScaleByZoom(vp->width, vp->zoom);
    01476   tmp_dpi.height = ScaleByZoom(vp->height, vp->zoom);
    01477
    01478   ViewportAddVehicles(&tmp_dpi);
    01479   DrawTextEffects(&tmp_dpi);
    01480
    01481   ViewportAddTownNames(&_vd.dpi);
    01482   ViewportAddStationNames(&_vd.dpi);
    01483   ViewportAddSigns(&_vd.dpi);
    01484
    01485   DrawTextEffects(&_vd.dpi);
    01486
    01487   if (_vd.tile_sprites_to_draw.Length() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
    01488
    01489   ParentSpriteToDraw *psd_end = _vd.parent_sprites_to_draw.End();
    01490   for (ParentSpriteToDraw *it = _vd.parent_sprites_to_draw.Begin(); it != psd_end; it++) {
    01491     *_vd.parent_sprites_to_sort.Append() = it;
    01492   }
    01493
    01494   ViewportSortParentSprites(&_vd.parent_sprites_to_sort);
    01495   ViewportDrawParentSprites(&_vd.parent_sprites_to_sort, &_vd.child_screen_sprites_to_draw);
    01496
    01497   if (_draw_bounding_boxes) ViewportDrawBoundingBoxes(&_vd.parent_sprites_to_sort);
    01498
    01499   if (_vd.string_sprites_to_draw.Length() != 0) ViewportDrawStrings(&_vd.dpi, &_vd.string_sprites_to_draw);
    01500
    01501   _cur_dpi = old_dpi;
    01502
    01503   _vd.string_sprites_to_draw.Clear();
    01504   _vd.tile_sprites_to_draw.Clear();
    01505   _vd.parent_sprites_to_draw.Clear();
    01506   _vd.parent_sprites_to_sort.Clear();
    01507   _vd.child_screen_sprites_to_draw.Clear();
    01508 }
    01509
    01514 static void ViewportDrawChk(const ViewPort *vp, int left, int top, int right, int bottom)
    01515 {
    01516   if (ScaleByZoom(bottom - top, vp->zoom) * ScaleByZoom(right - left, vp->zoom)
    01517   > 50000) {
    01518     if ((bottom - top) > (right - left)) {
    01519       int t = (top + bottom) >> 1;
    01520       ViewportDrawChk(vp, left, top, right, t);
    01521       ViewportDrawChk(vp, left, t, right, bottom);
    01522     } else {
    01523       int t = (left + right) >> 1;
    01524       ViewportDrawChk(vp, left, top, t, bottom);
    01525       ViewportDrawChk(vp, t, top, right, bottom);
    01526     }
    01527   } else {
    01528     ViewportDoDraw(vp, left, top, right, bottom);
    01529   }
    01530 }
    01531
    01532 static inline void ViewportDraw(const ViewPort *vp, int left, int top, int right, int bottom)
    01533 {
    01534   if (right <= vp->left || bottom <= vp->top) return;
    01535
    01536   if (left >= vp->left + vp->width) return;
    01537
    01538   if (left < vp->left) left = vp->left;
    01539   if (right > vp->left + vp->width) right = vp->left + vp->width;
    01540
    01541   if (top >= vp->top + vp->height) return;
    01542
    01543   if (top < vp->top) top = vp->top;
    01544   if (bottom > vp->top + vp->height) bottom = vp->top + vp->height;
    01545
    01546   ViewportDrawChk(vp, left, top, right, bottom);
    01547 }
    01548
    01552 void Window::DrawViewport() const
    01553 {
    01554   DrawPixelInfo *dpi = _cur_dpi;
    01555
    01556   dpi->left += this->left;
    01557   dpi->top += this->top;
    01558
    01559   ViewportDraw(this->viewport, dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height);
    01560
    01561   dpi->left -= this->left;
    01562   dpi->top -= this->top;
    01563 }
    01564
    01565 static inline void ClampViewportToMap(const ViewPort *vp, int &x, int &y)
    01566 {
    01567   /* Centre of the viewport is hot spot */
    01568   x += vp->virtual_width / 2;
    01569   y += vp->virtual_height / 2;
    01570
    01571   /* Convert viewport coordinates to map coordinates
    01572    * Calculation is scaled by 4 to avoid rounding errors */
    01573   int vx = -x + y * 2;
    01574   int vy =  x + y * 2;
    01575
    01576   /* clamp to size of map */
    01577   vx = Clamp(vx, 0, MapMaxX() * TILE_SIZE * 4);
    01578   vy = Clamp(vy, 0, MapMaxY() * TILE_SIZE * 4);
    01579
    01580   /* Convert map coordinates to viewport coordinates */
    01581   x = (-vx + vy) / 2;
    01582   y = ( vx + vy) / 4;
    01583
    01584   /* Remove centering */
    01585   x -= vp->virtual_width / 2;
    01586   y -= vp->virtual_height / 2;
    01587 }
    01588
    01593 void UpdateViewportPosition(Window *w)
    01594 {
    01595   const ViewPort *vp = w->viewport;
    01596
    01597   if (w->viewport->follow_vehicle != INVALID_VEHICLE) {
    01598     const Vehicle *veh = Vehicle::Get(w->viewport->follow_vehicle);
    01599     Point pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
    01600
    01601     w->viewport->scrollpos_x = pt.x;
    01602     w->viewport->scrollpos_y = pt.y;
    01603     SetViewportPosition(w, pt.x, pt.y);
    01604   } else {
    01605     /* Ensure the destination location is within the map */
    01606     ClampViewportToMap(vp, w->viewport->dest_scrollpos_x, w->viewport->dest_scrollpos_y);
    01607
    01608     int delta_x = w->viewport->dest_scrollpos_x - w->viewport->scrollpos_x;
    01609     int delta_y = w->viewport->dest_scrollpos_y - w->viewport->scrollpos_y;
    01610
    01611     if (delta_x != 0 || delta_y != 0) {
    01612       if (_settings_client.gui.smooth_scroll) {
    01613         int max_scroll = ScaleByMapSize1D(512);
    01614         /* Not at our desired position yet... */
    01615         w->viewport->scrollpos_x += Clamp(delta_x / 4, -max_scroll, max_scroll);
    01616         w->viewport->scrollpos_y += Clamp(delta_y / 4, -max_scroll, max_scroll);
    01617       } else {
    01618         w->viewport->scrollpos_x = w->viewport->dest_scrollpos_x;
    01619         w->viewport->scrollpos_y = w->viewport->dest_scrollpos_y;
    01620       }
    01621     }
    01622
    01623     ClampViewportToMap(vp, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
    01624
    01625     SetViewportPosition(w, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
    01626   }
    01627 }
    01628
    01638 static void MarkViewportDirty(const ViewPort *vp, int left, int top, int right, int bottom)
    01639 {
    01640   left = UnScaleByZoom(left, vp->zoom);
    01641   top  = UnScaleByZoom(top, vp->zoom);
    01642   right = UnScaleByZoom(right, vp->zoom);
    01643   bottom = UnScaleByZoom(bottom, vp->zoom);
    01644
    01645   int vl = vp->virtual_left;
    01646   int vt = vp->virtual_top;
    01647   int w  = vp->width;
    01648   int h  = vp->height;
    01649
    01650   left = max(0, left - vl);
    01651   if (left >= w) return;
    01652
    01653   top = max(0, top - vt);
    01654   if (top >= h ) return;
    01655
    01656   right -= vl;
    01657   if (right <= 0) return;
    01658
    01659   bottom -= vt;
    01660   if (bottom <= 0) return;
    01661
    01662   SetDirtyBlocks(left + vp->left, top + vp->top, right + vp->left, bottom + vp->top);
    01663 }
    01664
    01673 void MarkAllViewportsDirty(int left, int top, int right, int bottom)
    01674 {
    01675   Window *w;
    01676   FOR_ALL_WINDOWS_FROM_BACK(w) {
    01677     ViewPort *vp = w->viewport;
    01678     if (vp != NULL) {
    01679       assert(vp->width != 0);
    01680       MarkViewportDirty(vp, left, top, right, bottom);
    01681     }
    01682   }
    01683 }
    01684
    01690 void MarkTileDirtyByTile(TileIndex tile)
    01691 {
    01692   Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, GetTileZ(tile));
    01693   MarkAllViewportsDirty(
    01694     pt.x - 31,
    01695     pt.y - 122,
    01696     pt.x - 31 + 67,
    01697     pt.y - 122 + 154
    01698   );
    01699 }
    01700
    01708 static void SetSelectionTilesDirty()
    01709 {
    01710   int x_size = _thd.size.x;
    01711   int y_size = _thd.size.y;
    01712
    01713   if (!_thd.diagonal) { // Selecting in a straigth rectangle (or a single square)
    01714     int x_start = _thd.pos.x;
    01715     int y_start = _thd.pos.y;
    01716
    01717     if (_thd.outersize.x != 0) {
    01718       x_size  += _thd.outersize.x;
    01719       x_start += _thd.offs.x;
    01720       y_size  += _thd.outersize.y;
    01721       y_start += _thd.offs.y;
    01722     }
    01723
    01724     x_size -= TILE_SIZE;
    01725     y_size -= TILE_SIZE;
    01726
    01727     assert(x_size >= 0);
    01728     assert(y_size >= 0);
    01729
    01730     int x_end = Clamp(x_start + x_size, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
    01731     int y_end = Clamp(y_start + y_size, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
    01732
    01733     x_start = Clamp(x_start, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
    01734     y_start = Clamp(y_start, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
    01735
    01736     /* make sure everything is multiple of TILE_SIZE */
    01737     assert((x_end | y_end | x_start | y_start) % TILE_SIZE == 0);
    01738
    01739     /* How it works:
    01740      * Suppose we have to mark dirty rectangle of 3x4 tiles:
    01741      *   x
    01742      *  xxx
    01743      * xxxxx
    01744      *  xxxxx
    01745      *   xxx
    01746      *    x
    01747      * This algorithm marks dirty columns of tiles, so it is done in 3+4-1 steps:
    01748      * 1)  x     2)  x
    01749      *    xxx       Oxx
    01750      *   Oxxxx     xOxxx
    01751      *    xxxxx     Oxxxx
    01752      *     xxx       xxx
    01753      *      x         x
    01754      * And so forth...
    01755      */
    01756
    01757     int top_x = x_end; // coordinates of top dirty tile
    01758     int top_y = y_start;
    01759     int bot_x = top_x; // coordinates of bottom dirty tile
    01760     int bot_y = top_y;
    01761
    01762     do {
    01763       Point top = RemapCoords2(top_x, top_y); // topmost dirty point
    01764       Point bot = RemapCoords2(bot_x + TILE_SIZE - 1, bot_y + TILE_SIZE - 1); // bottommost point
    01765
    01766       /* the 'x' coordinate of 'top' and 'bot' is the same (and always in the same distance from tile middle),
    01767        * tile height/slope affects only the 'y' on-screen coordinate! */
    01768
    01769       int l = top.x - (TILE_PIXELS - 2); // 'x' coordinate of left side of dirty rectangle
    01770       int t = top.y;                     // 'y' coordinate of top side -//-
    01771       int r = top.x + (TILE_PIXELS - 2); // right side of dirty rectangle
    01772       int b = bot.y;                     // bottom -//-
    01773
    01774       static const int OVERLAY_WIDTH = 4; // part of selection sprites is drawn outside the selected area
    01775
    01776       /* For halftile foundations on SLOPE_STEEP_S the sprite extents some more towards the top */
    01777       MarkAllViewportsDirty(l - OVERLAY_WIDTH, t - OVERLAY_WIDTH - TILE_HEIGHT, r + OVERLAY_WIDTH, b + OVERLAY_WIDTH);
    01778
    01779       /* haven't we reached the topmost tile yet? */
    01780       if (top_x != x_start) {
    01781         top_x -= TILE_SIZE;
    01782       } else {
    01783         top_y += TILE_SIZE;
    01784       }
    01785
    01786       /* the way the bottom tile changes is different when we reach the bottommost tile */
    01787       if (bot_y != y_end) {
    01788         bot_y += TILE_SIZE;
    01789       } else {
    01790         bot_x -= TILE_SIZE;
    01791       }
    01792     } while (bot_x >= top_x);
    01793   } else { // Selecting in a 45 degrees rotated (diagonal) rectangle.
    01794     /* a_size, b_size describe a rectangle with rotated coordinates */
    01795     int a_size = x_size + y_size, b_size = x_size - y_size;
    01796
    01797     int interval_a = a_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
    01798     int interval_b = b_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
    01799
    01800     for (int a = -interval_a; a != a_size + interval_a; a += interval_a) {
    01801       for (int b = -interval_b; b != b_size + interval_b; b += interval_b) {
    01802         uint x = (_thd.pos.x + (a + b) / 2) / TILE_SIZE;
    01803         uint y = (_thd.pos.y + (a - b) / 2) / TILE_SIZE;
    01804
    01805         if (x < MapMaxX() && y < MapMaxY()) {
    01806           MarkTileDirtyByTile(TileXY(x, y));
    01807         }
    01808       }
    01809     }
    01810   }
    01811 }
    01812
    01813
    01814 void SetSelectionRed(bool b)
    01815 {
    01816   _thd.make_square_red = b;
    01817   SetSelectionTilesDirty();
    01818 }
    01819
    01828 static bool CheckClickOnViewportSign(const ViewPort *vp, int x, int y, const ViewportSign *sign)
    01829 {
    01830   bool small = (vp->zoom >= ZOOM_LVL_OUT_4X);
    01831   int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, vp->zoom);
    01832   int sign_height = ScaleByZoom(VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM, vp->zoom);
    01833
    01834   x = ScaleByZoom(x - vp->left + vp->virtual_left, vp->zoom);
    01835   y = ScaleByZoom(y - vp->top + vp->virtual_top, vp->zoom);
    01836
    01837   return y >= sign->top && y < sign->top + sign_height &&
    01838       x >= sign->center - sign_half_width && x < sign->center + sign_half_width;
    01839 }
    01840
    01841 static bool CheckClickOnTown(const ViewPort *vp, int x, int y)
    01842 {
    01843   if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES)) return false;
    01844
    01845   const Town *t;
    01846   FOR_ALL_TOWNS(t) {
    01847     if (CheckClickOnViewportSign(vp, x, y, &t->sign)) {
    01848       ShowTownViewWindow(t->index);
    01849       return true;
    01850     }
    01851   }
    01852
    01853   return false;
    01854 }
    01855
    01856 static bool CheckClickOnStation(const ViewPort *vp, int x, int y)
    01857 {
    01858   if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || IsInvisibilitySet(TO_SIGNS)) return false;
    01859
    01860   const BaseStation *st;
    01861   FOR_ALL_BASE_STATIONS(st) {
    01862     /* Check whether the base station is a station or a waypoint */
    01863     bool is_station = Station::IsExpected(st);
    01864
    01865     /* Don't check if the display options are disabled */
    01866     if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
    01867
    01868     if (CheckClickOnViewportSign(vp, x, y, &st->sign)) {
    01869       if (is_station) {
    01870         ShowStationViewWindow(st->index);
    01871       } else {
    01872         ShowWaypointWindow(Waypoint::From(st));
    01873       }
    01874       return true;
    01875     }
    01876   }
    01877
    01878   return false;
    01879 }
    01880
    01881
    01882 static bool CheckClickOnSign(const ViewPort *vp, int x, int y)
    01883 {
    01884   /* Signs are turned off, or they are transparent and invisibility is ON, or company is a spectator */
    01885   if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS) || _local_company == COMPANY_SPECTATOR) return false;
    01886
    01887   const Sign *si;
    01888   FOR_ALL_SIGNS(si) {
    01889     if (CheckClickOnViewportSign(vp, x, y, &si->sign)) {
    01890       HandleClickOnSign(si);
    01891       return true;
    01892     }
    01893   }
    01894
    01895   return false;
    01896 }
    01897
    01898
    01899 static bool CheckClickOnLandscape(const ViewPort *vp, int x, int y)
    01900 {
    01901   Point pt = TranslateXYToTileCoord(vp, x, y);
    01902
    01903   if (pt.x != -1) return ClickTile(TileVirtXY(pt.x, pt.y));
    01904   return true;
    01905 }
    01906
    01907 static void PlaceObject()
    01908 {
    01909   Point pt;
    01910   Window *w;
    01911
    01912   pt = GetTileBelowCursor();
    01913   if (pt.x == -1) return;
    01914
    01915   if ((_thd.place_mode & HT_DRAG_MASK) == HT_POINT) {
    01916     pt.x += 8;
    01917     pt.y += 8;
    01918   }
    01919
    01920   _tile_fract_coords.x = pt.x & TILE_UNIT_MASK;
    01921   _tile_fract_coords.y = pt.y & TILE_UNIT_MASK;
    01922
    01923   w = _thd.GetCallbackWnd();
    01924   if (w != NULL) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
    01925 }
    01926
    01927
    01928 bool HandleViewportClicked(const ViewPort *vp, int x, int y)
    01929 {
    01930   const Vehicle *v = CheckClickOnVehicle(vp, x, y);
    01931
    01932   if (_thd.place_mode & HT_VEHICLE) {
    01933     if (v != NULL && VehicleClicked(v)) return true;
    01934   }
    01935
    01936   /* Vehicle placement mode already handled above. */
    01937   if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
    01938     PlaceObject();
    01939     return true;
    01940   }
    01941
    01942   if (CheckClickOnTown(vp, x, y)) return true;
    01943   if (CheckClickOnStation(vp, x, y)) return true;
    01944   if (CheckClickOnSign(vp, x, y)) return true;
    01945   bool result = CheckClickOnLandscape(vp, x, y);
    01946
    01947   if (v != NULL) {
    01948     DEBUG(misc, 2, "Vehicle %d (index %d) at %p", v->unitnumber, v->index, v);
    01949     if (IsCompanyBuildableVehicleType(v)) {
    01950       v = v->First();
    01951       if (_ctrl_pressed && v->owner == _local_company) {
    01952         StartStopVehicle(v, true);
    01953       } else {
    01954         ShowVehicleViewWindow(v);
    01955       }
    01956     }
    01957     return true;
    01958   }
    01959   return result;
    01960 }
    01961
    01962
    01972 bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
    01973 {
    01974   /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
    01975   if (z == -1) z = GetSlopeZ(Clamp(x, 0, MapSizeX() * TILE_SIZE - 1), Clamp(y, 0, MapSizeY() * TILE_SIZE - 1));
    01976
    01977   Point pt = MapXYZToViewport(w->viewport, x, y, z);
    01978   w->viewport->follow_vehicle = INVALID_VEHICLE;
    01979
    01980   if (w->viewport->dest_scrollpos_x == pt.x && w->viewport->dest_scrollpos_y == pt.y) return false;
    01981
    01982   if (instant) {
    01983     w->viewport->scrollpos_x = pt.x;
    01984     w->viewport->scrollpos_y = pt.y;
    01985   }
    01986
    01987   w->viewport->dest_scrollpos_x = pt.x;
    01988   w->viewport->dest_scrollpos_y = pt.y;
    01989   return true;
    01990 }
    01991
    01999 bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
    02000 {
    02001   return ScrollWindowTo(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, -1, w, instant);
    02002 }
    02003
    02010 bool ScrollMainWindowToTile(TileIndex tile, bool instant)
    02011 {
    02012   return ScrollMainWindowTo(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, -1, instant);
    02013 }
    02014
    02019 void SetRedErrorSquare(TileIndex tile)
    02020 {
    02021   TileIndex old;
    02022
    02023   old = _thd.redsq;
    02024   _thd.redsq = tile;
    02025
    02026   if (tile != old) {
    02027     if (tile != INVALID_TILE) MarkTileDirtyByTile(tile);
    02028     if (old  != INVALID_TILE) MarkTileDirtyByTile(old);
    02029   }
    02030 }
    02031
    02037 void SetTileSelectSize(int w, int h)
    02038 {
    02039   _thd.new_size.x = w * TILE_SIZE;
    02040   _thd.new_size.y = h * TILE_SIZE;
    02041   _thd.new_outersize.x = 0;
    02042   _thd.new_outersize.y = 0;
    02043 }
    02044
    02045 void SetTileSelectBigSize(int ox, int oy, int sx, int sy)
    02046 {
    02047   _thd.offs.x = ox * TILE_SIZE;
    02048   _thd.offs.y = oy * TILE_SIZE;
    02049   _thd.new_outersize.x = sx * TILE_SIZE;
    02050   _thd.new_outersize.y = sy * TILE_SIZE;
    02051 }
    02052
    02054 static HighLightStyle GetAutorailHT(int x, int y)
    02055 {
    02056   return HT_RAIL | _autorail_piece[x & TILE_UNIT_MASK][y & TILE_UNIT_MASK];
    02057 }
    02058
    02062 void TileHighlightData::Reset()
    02063 {
    02064   this->pos.x = 0;
    02065   this->pos.y = 0;
    02066   this->new_pos.x = 0;
    02067   this->new_pos.y = 0;
    02068 }
    02069
    02074 bool TileHighlightData::IsDraggingDiagonal()
    02075 {
    02076   return (this->place_mode & HT_DIAGONAL) != 0 && _ctrl_pressed && _left_button_down;
    02077 }
    02078
    02083 Window *TileHighlightData::GetCallbackWnd()
    02084 {
    02085   return FindWindowById(this->window_class, this->window_number);
    02086 }
    02087
    02088
    02089
    02097 void UpdateTileSelection()
    02098 {
    02099   int x1;
    02100   int y1;
    02101
    02102   HighLightStyle new_drawstyle = HT_NONE;
    02103   bool new_diagonal = false;
    02104
    02105   if ((_thd.place_mode & HT_DRAG_MASK) == HT_SPECIAL) {
    02106     x1 = _thd.selend.x;
    02107     y1 = _thd.selend.y;
    02108     if (x1 != -1) {
    02109       int x2 = _thd.selstart.x & ~TILE_UNIT_MASK;
    02110       int y2 = _thd.selstart.y & ~TILE_UNIT_MASK;
    02111       x1 &= ~TILE_UNIT_MASK;
    02112       y1 &= ~TILE_UNIT_MASK;
    02113
    02114       if (_thd.IsDraggingDiagonal()) {
    02115         new_diagonal = true;
    02116       } else {
    02117         if (x1 >= x2) Swap(x1, x2);
    02118         if (y1 >= y2) Swap(y1, y2);
    02119       }
    02120       _thd.new_pos.x = x1;
    02121       _thd.new_pos.y = y1;
    02122       _thd.new_size.x = x2 - x1;
    02123       _thd.new_size.y = y2 - y1;
    02124       if (!new_diagonal) {
    02125         _thd.new_size.x += TILE_SIZE;
    02126         _thd.new_size.y += TILE_SIZE;
    02127       }
    02128       new_drawstyle = _thd.next_drawstyle;
    02129     }
    02130   } else if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
    02131     Point pt = GetTileBelowCursor();
    02132     x1 = pt.x;
    02133     y1 = pt.y;
    02134     if (x1 != -1) {
    02135       switch (_thd.place_mode & HT_DRAG_MASK) {
    02136         case HT_RECT:
    02137           new_drawstyle = HT_RECT;
    02138           break;
    02139         case HT_POINT:
    02140           new_drawstyle = HT_POINT;
    02141           x1 += TILE_SIZE / 2;
    02142           y1 += TILE_SIZE / 2;
    02143           break;
    02144         case HT_RAIL:
    02145           /* Draw one highlighted tile in any direction */
    02146           new_drawstyle = GetAutorailHT(pt.x, pt.y);
    02147           break;
    02148         case HT_LINE:
    02149           switch (_thd.place_mode & HT_DIR_MASK) {
    02150             case HT_DIR_X: new_drawstyle = HT_LINE | HT_DIR_X; break;
    02151             case HT_DIR_Y: new_drawstyle = HT_LINE | HT_DIR_Y; break;
    02152
    02153             case HT_DIR_HU:
    02154             case HT_DIR_HL:
    02155               new_drawstyle = (pt.x & TILE_UNIT_MASK) + (pt.y & TILE_UNIT_MASK) <= TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
    02156               break;
    02157
    02158             case HT_DIR_VL:
    02159             case HT_DIR_VR:
    02160               new_drawstyle = (pt.x & TILE_UNIT_MASK) > (pt.y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02161               break;
    02162
    02163             default: NOT_REACHED();
    02164           }
    02165           _thd.selstart.x = x1 & ~TILE_UNIT_MASK;
    02166           _thd.selstart.y = y1 & ~TILE_UNIT_MASK;
    02167           break;
    02168         default:
    02169           NOT_REACHED();
    02170           break;
    02171       }
    02172       _thd.new_pos.x = x1 & ~TILE_UNIT_MASK;
    02173       _thd.new_pos.y = y1 & ~TILE_UNIT_MASK;
    02174     }
    02175   }
    02176
    02177   /* redraw selection */
    02178   if (_thd.drawstyle != new_drawstyle ||
    02179       _thd.pos.x != _thd.new_pos.x || _thd.pos.y != _thd.new_pos.y ||
    02180       _thd.size.x != _thd.new_size.x || _thd.size.y != _thd.new_size.y ||
    02181       _thd.outersize.x != _thd.new_outersize.x ||
    02182       _thd.outersize.y != _thd.new_outersize.y ||
    02183       _thd.diagonal    != new_diagonal) {
    02184     /* Clear the old tile selection? */
    02185     if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
    02186
    02187     _thd.drawstyle = new_drawstyle;
    02188     _thd.pos = _thd.new_pos;
    02189     _thd.size = _thd.new_size;
    02190     _thd.outersize = _thd.new_outersize;
    02191     _thd.diagonal = new_diagonal;
    02192     _thd.dirty = 0xff;
    02193
    02194     /* Draw the new tile selection? */
    02195     if ((new_drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
    02196   }
    02197 }
    02198
    02206 static inline void ShowMeasurementTooltips(StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_cond = TCC_LEFT_CLICK)
    02207 {
    02208   if (!_settings_client.gui.measure_tooltip) return;
    02209   GuiShowTooltips(_thd.GetCallbackWnd(), str, paramcount, params, close_cond);
    02210 }
    02211
    02213 void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
    02214 {
    02215   _thd.select_method = method;
    02216   _thd.select_proc   = process;
    02217   _thd.selend.x = TileX(tile) * TILE_SIZE;
    02218   _thd.selstart.x = TileX(tile) * TILE_SIZE;
    02219   _thd.selend.y = TileY(tile) * TILE_SIZE;
    02220   _thd.selstart.y = TileY(tile) * TILE_SIZE;
    02221
    02222   /* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
    02223    * In effect, placement starts from the centre of a tile
    02224    */
    02225   if (method == VPM_X_OR_Y || method == VPM_FIX_X || method == VPM_FIX_Y) {
    02226     _thd.selend.x += TILE_SIZE / 2;
    02227     _thd.selend.y += TILE_SIZE / 2;
    02228     _thd.selstart.x += TILE_SIZE / 2;
    02229     _thd.selstart.y += TILE_SIZE / 2;
    02230   }
    02231
    02232   HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
    02233   if ((_thd.place_mode & HT_DRAG_MASK) == HT_RECT) {
    02234     _thd.place_mode = HT_SPECIAL | others;
    02235     _thd.next_drawstyle = HT_RECT | others;
    02236   } else if (_thd.place_mode & (HT_RAIL | HT_LINE)) {
    02237     _thd.place_mode = HT_SPECIAL | others;
    02238     _thd.next_drawstyle = _thd.drawstyle | others;
    02239   } else {
    02240     _thd.place_mode = HT_SPECIAL | others;
    02241     _thd.next_drawstyle = HT_POINT | others;
    02242   }
    02243   _special_mouse_mode = WSM_SIZING;
    02244 }
    02245
    02246 void VpSetPlaceSizingLimit(int limit)
    02247 {
    02248   _thd.sizelimit = limit;
    02249 }
    02250
    02256 void VpSetPresizeRange(TileIndex from, TileIndex to)
    02257 {
    02258   uint64 distance = DistanceManhattan(from, to) + 1;
    02259
    02260   _thd.selend.x = TileX(to) * TILE_SIZE;
    02261   _thd.selend.y = TileY(to) * TILE_SIZE;
    02262   _thd.selstart.x = TileX(from) * TILE_SIZE;
    02263   _thd.selstart.y = TileY(from) * TILE_SIZE;
    02264   _thd.next_drawstyle = HT_RECT;
    02265
    02266   /* show measurement only if there is any length to speak of */
    02267   if (distance > 1) ShowMeasurementTooltips(STR_MEASURE_LENGTH, 1, &distance, TCC_HOVER);
    02268 }
    02269
    02270 static void VpStartPreSizing()
    02271 {
    02272   _thd.selend.x = -1;
    02273   _special_mouse_mode = WSM_PRESIZE;
    02274 }
    02275
    02280 static HighLightStyle Check2x1AutoRail(int mode)
    02281 {
    02282   int fxpy = _tile_fract_coords.x + _tile_fract_coords.y;
    02283   int sxpy = (_thd.selend.x & TILE_UNIT_MASK) + (_thd.selend.y & TILE_UNIT_MASK);
    02284   int fxmy = _tile_fract_coords.x - _tile_fract_coords.y;
    02285   int sxmy = (_thd.selend.x & TILE_UNIT_MASK) - (_thd.selend.y & TILE_UNIT_MASK);
    02286
    02287   switch (mode) {
    02288     default: NOT_REACHED();
    02289     case 0: // end piece is lower right
    02290       if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
    02291       if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
    02292       return HT_DIR_Y;
    02293
    02294     case 1:
    02295       if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
    02296       if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
    02297       return HT_DIR_Y;
    02298
    02299     case 2:
    02300       if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
    02301       if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
    02302       return HT_DIR_X;
    02303
    02304     case 3:
    02305       if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
    02306       if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
    02307       return HT_DIR_X;
    02308   }
    02309 }
    02310
    02324 static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
    02325 {
    02326   uint start_x = TileX(start_tile);
    02327   uint start_y = TileY(start_tile);
    02328   uint end_x = TileX(end_tile);
    02329   uint end_y = TileY(end_tile);
    02330
    02331   switch (style & HT_DRAG_MASK) {
    02332     case HT_RAIL:
    02333     case HT_LINE: return (end_x > start_x || (end_x == start_x && end_y > start_y));
    02334
    02335     case HT_RECT:
    02336     case HT_POINT: return (end_x != start_x && end_y < start_y);
    02337     default: NOT_REACHED();
    02338   }
    02339
    02340   return false;
    02341 }
    02342
    02358 static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
    02359 {
    02360   bool swap = SwapDirection(style, start_tile, end_tile);
    02361   uint h0, h1; // Start height and end height.
    02362
    02363   if (start_tile == end_tile) return 0;
    02364   if (swap) Swap(start_tile, end_tile);
    02365
    02366   switch (style & HT_DRAG_MASK) {
    02367     case HT_RECT: {
    02368       static const TileIndexDiffC heightdiff_area_by_dir[] = {
    02369         /* Start */ {1, 0}, /* Dragging east */ {0, 0}, // Dragging south
    02370         /* End   */ {0, 1}, /* Dragging east */ {1, 1}  // Dragging south
    02371       };
    02372
    02373       /* In the case of an area we can determine whether we were dragging south or
    02374        * east by checking the X-coordinates of the tiles */
    02375       byte style_t = (byte)(TileX(end_tile) > TileX(start_tile));
    02376       start_tile = TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_area_by_dir[style_t]));
    02377       end_tile   = TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_area_by_dir[2 + style_t]));
    02378       /* FALL THROUGH */
    02379     }
    02380
    02381     case HT_POINT:
    02382       h0 = TileHeight(start_tile);
    02383       h1 = TileHeight(end_tile);
    02384       break;
    02385     default: { // All other types, this is mostly only line/autorail
    02386       static const HighLightStyle flip_style_direction[] = {
    02387         HT_DIR_X, HT_DIR_Y, HT_DIR_HL, HT_DIR_HU, HT_DIR_VR, HT_DIR_VL
    02388       };
    02389       static const TileIndexDiffC heightdiff_line_by_dir[] = {
    02390         /* Start */ {1, 0}, {1, 1}, /* HT_DIR_X  */ {0, 1}, {1, 1}, // HT_DIR_Y
    02391         /* Start */ {1, 0}, {0, 0}, /* HT_DIR_HU */ {1, 0}, {1, 1}, // HT_DIR_HL
    02392         /* Start */ {1, 0}, {1, 1}, /* HT_DIR_VL */ {0, 1}, {1, 1}, // HT_DIR_VR
    02393
    02394         /* Start */ {0, 1}, {0, 0}, /* HT_DIR_X  */ {1, 0}, {0, 0}, // HT_DIR_Y
    02395         /* End   */ {0, 1}, {0, 0}, /* HT_DIR_HU */ {1, 1}, {0, 1}, // HT_DIR_HL
    02396         /* End   */ {1, 0}, {0, 0}, /* HT_DIR_VL */ {0, 0}, {0, 1}, // HT_DIR_VR
    02397       };
    02398
    02399       distance %= 2; // we're only interested if the distance is even or uneven
    02400       style &= HT_DIR_MASK;
    02401
    02402       /* To handle autorail, we do some magic to be able to use a lookup table.
    02403        * Firstly if we drag the other way around, we switch start&end, and if needed
    02404        * also flip the drag-position. Eg if it was on the left, and the distance is even
    02405        * that means the end, which is now the start is on the right */
    02406       if (swap && distance == 0) style = flip_style_direction[style];
    02407
    02408       /* Use lookup table for start-tile based on HighLightStyle direction */
    02409       byte style_t = style * 2;
    02410       assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
    02411       h0 = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t])));
    02412       uint ht = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t + 1])));
    02413       h0 = max(h0, ht);
    02414
    02415       /* Use lookup table for end-tile based on HighLightStyle direction
    02416        * flip around side (lower/upper, left/right) based on distance */
    02417       if (distance == 0) style_t = flip_style_direction[style] * 2;
    02418       assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
    02419       h1 = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t])));
    02420       ht = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t + 1])));
    02421       h1 = max(h1, ht);
    02422       break;
    02423     }
    02424   }
    02425
    02426   if (swap) Swap(h0, h1);
    02427   return (int)(h1 - h0) * TILE_HEIGHT_STEP;
    02428 }
    02429
    02430 static const StringID measure_strings_length[] = {STR_NULL, STR_MEASURE_LENGTH, STR_MEASURE_LENGTH_HEIGHTDIFF};
    02431
    02438 static void CheckUnderflow(int &test, int &other, int mult)
    02439 {
    02440   if (test >= 0) return;
    02441
    02442   other += mult * test;
    02443   test = 0;
    02444 }
    02445
    02453 static void CheckOverflow(int &test, int &other, int max, int mult)
    02454 {
    02455   if (test <= max) return;
    02456
    02457   other += mult * (test - max);
    02458   test = max;
    02459 }
    02460
    02462 static void CalcRaildirsDrawstyle(int x, int y, int method)
    02463 {
    02464   HighLightStyle b;
    02465
    02466   int dx = _thd.selstart.x - (_thd.selend.x & ~TILE_UNIT_MASK);
    02467   int dy = _thd.selstart.y - (_thd.selend.y & ~TILE_UNIT_MASK);
    02468   uint w = abs(dx) + TILE_SIZE;
    02469   uint h = abs(dy) + TILE_SIZE;
    02470
    02471   if (method & ~(VPM_RAILDIRS | VPM_SIGNALDIRS)) {
    02472     /* We 'force' a selection direction; first four rail buttons. */
    02473     method &= ~(VPM_RAILDIRS | VPM_SIGNALDIRS);
    02474     int raw_dx = _thd.selstart.x - _thd.selend.x;
    02475     int raw_dy = _thd.selstart.y - _thd.selend.y;
    02476     switch (method) {
    02477       case VPM_FIX_X:
    02478         b = HT_LINE | HT_DIR_Y;
    02479         x = _thd.selstart.x;
    02480         break;
    02481
    02482       case VPM_FIX_Y:
    02483         b = HT_LINE | HT_DIR_X;
    02484         y = _thd.selstart.y;
    02485         break;
    02486
    02487       case VPM_FIX_HORIZONTAL:
    02488         if (dx == -dy) {
    02489           /* We are on a straight horizontal line. Determine the 'rail'
    02490            * to build based the sub tile location. */
    02491           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
    02492         } else {
    02493           /* We are not on a straight line. Determine the rail to build
    02494            * based on whether we are above or below it. */
    02495           b = dx + dy >= (int)TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
    02496
    02497           /* Calculate where a horizontal line through the start point and
    02498            * a vertical line from the selected end point intersect and
    02499            * use that point as the end point. */
    02500           int offset = (raw_dx - raw_dy) / 2;
    02501           x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
    02502           y = _thd.selstart.y + (offset & ~TILE_UNIT_MASK);
    02503
    02504           /* 'Build' the last half rail tile if needed */
    02505           if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
    02506             if (dx + dy >= (int)TILE_SIZE) {
    02507               x += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
    02508             } else {
    02509               y += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
    02510             }
    02511           }
    02512
    02513           /* Make sure we do not overflow the map! */
    02514           CheckUnderflow(x, y, 1);
    02515           CheckUnderflow(y, x, 1);
    02516           CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, 1);
    02517           CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, 1);
    02518           assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
    02519         }
    02520         break;
    02521
    02522       case VPM_FIX_VERTICAL:
    02523         if (dx == dy) {
    02524           /* We are on a straight vertical line. Determine the 'rail'
    02525            * to build based the sub tile location. */
    02526           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02527         } else {
    02528           /* We are not on a straight line. Determine the rail to build
    02529            * based on whether we are left or right from it. */
    02530           b = dx < dy ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02531
    02532           /* Calculate where a vertical line through the start point and
    02533            * a horizontal line from the selected end point intersect and
    02534            * use that point as the end point. */
    02535           int offset = (raw_dx + raw_dy + (int)TILE_SIZE) / 2;
    02536           x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
    02537           y = _thd.selstart.y - (offset & ~TILE_UNIT_MASK);
    02538
    02539           /* 'Build' the last half rail tile if needed */
    02540           if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
    02541             if (dx - dy < 0) {
    02542               y += (dx > dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
    02543             } else {
    02544               x += (dx < dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
    02545             }
    02546           }
    02547
    02548           /* Make sure we do not overflow the map! */
    02549           CheckUnderflow(x, y, -1);
    02550           CheckUnderflow(y, x, -1);
    02551           CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, -1);
    02552           CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, -1);
    02553           assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
    02554         }
    02555         break;
    02556
    02557       default:
    02558         NOT_REACHED();
    02559     }
    02560   } else if (TileVirtXY(_thd.selstart.x, _thd.selstart.y) == TileVirtXY(x, y)) { // check if we're only within one tile
    02561     if (method & VPM_RAILDIRS) {
    02562       b = GetAutorailHT(x, y);
    02563     } else { // rect for autosignals on one tile
    02564       b = HT_RECT;
    02565     }
    02566   } else if (h == TILE_SIZE) { // Is this in X direction?
    02567     if (dx == (int)TILE_SIZE) { // 2x1 special handling
    02568       b = (Check2x1AutoRail(3)) | HT_LINE;
    02569     } else if (dx == -(int)TILE_SIZE) {
    02570       b = (Check2x1AutoRail(2)) | HT_LINE;
    02571     } else {
    02572       b = HT_LINE | HT_DIR_X;
    02573     }
    02574     y = _thd.selstart.y;
    02575   } else if (w == TILE_SIZE) { // Or Y direction?
    02576     if (dy == (int)TILE_SIZE) { // 2x1 special handling
    02577       b = (Check2x1AutoRail(1)) | HT_LINE;
    02578     } else if (dy == -(int)TILE_SIZE) { // 2x1 other direction
    02579       b = (Check2x1AutoRail(0)) | HT_LINE;
    02580     } else {
    02581       b = HT_LINE | HT_DIR_Y;
    02582     }
    02583     x = _thd.selstart.x;
    02584   } else if (w > h * 2) { // still count as x dir?
    02585     b = HT_LINE | HT_DIR_X;
    02586     y = _thd.selstart.y;
    02587   } else if (h > w * 2) { // still count as y dir?
    02588     b = HT_LINE | HT_DIR_Y;
    02589     x = _thd.selstart.x;
    02590   } else { // complicated direction
    02591     int d = w - h;
    02592     _thd.selend.x = _thd.selend.x & ~TILE_UNIT_MASK;
    02593     _thd.selend.y = _thd.selend.y & ~TILE_UNIT_MASK;
    02594
    02595     /* four cases. */
    02596     if (x > _thd.selstart.x) {
    02597       if (y > _thd.selstart.y) {
    02598         /* south */
    02599         if (d == 0) {
    02600           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02601         } else if (d >= 0) {
    02602           x = _thd.selstart.x + h;
    02603           b = HT_LINE | HT_DIR_VL;
    02604         } else {
    02605           y = _thd.selstart.y + w;
    02606           b = HT_LINE | HT_DIR_VR;
    02607         }
    02608       } else {
    02609         /* west */
    02610         if (d == 0) {
    02611           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
    02612         } else if (d >= 0) {
    02613           x = _thd.selstart.x + h;
    02614           b = HT_LINE | HT_DIR_HL;
    02615         } else {
    02616           y = _thd.selstart.y - w;
    02617           b = HT_LINE | HT_DIR_HU;
    02618         }
    02619       }
    02620     } else {
    02621       if (y > _thd.selstart.y) {
    02622         /* east */
    02623         if (d == 0) {
    02624           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
    02625         } else if (d >= 0) {
    02626           x = _thd.selstart.x - h;
    02627           b = HT_LINE | HT_DIR_HU;
    02628         } else {
    02629           y = _thd.selstart.y + w;
    02630           b = HT_LINE | HT_DIR_HL;
    02631         }
    02632       } else {
    02633         /* north */
    02634         if (d == 0) {
    02635           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02636         } else if (d >= 0) {
    02637           x = _thd.selstart.x - h;
    02638           b = HT_LINE | HT_DIR_VR;
    02639         } else {
    02640           y = _thd.selstart.y - w;
    02641           b = HT_LINE | HT_DIR_VL;
    02642         }
    02643       }
    02644     }
    02645   }
    02646
    02647   if (_settings_client.gui.measure_tooltip) {
    02648     TileIndex t0 = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
    02649     TileIndex t1 = TileVirtXY(x, y);
    02650     uint distance = DistanceManhattan(t0, t1) + 1;
    02651     byte index = 0;
    02652     uint64 params[2];
    02653
    02654     if (distance != 1) {
    02655       int heightdiff = CalcHeightdiff(b, distance, t0, t1);
    02656       /* If we are showing a tooltip for horizontal or vertical drags,
    02657        * 2 tiles have a length of 1. To bias towards the ceiling we add
    02658        * one before division. It feels more natural to count 3 lengths as 2 */
    02659       if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
    02660         distance = CeilDiv(distance, 2);
    02661       }
    02662
    02663       params[index++] = distance;
    02664       if (heightdiff != 0) params[index++] = heightdiff;
    02665     }
    02666
    02667     ShowMeasurementTooltips(measure_strings_length[index], index, params);
    02668   }
    02669
    02670   _thd.selend.x = x;
    02671   _thd.selend.y = y;
    02672   _thd.next_drawstyle = b;
    02673 }
    02674
    02682 void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
    02683 {
    02684   int sx, sy;
    02685   HighLightStyle style;
    02686
    02687   if (x == -1) {
    02688     _thd.selend.x = -1;
    02689     return;
    02690   }
    02691
    02692   /* Special handling of drag in any (8-way) direction */
    02693   if (method & (VPM_RAILDIRS | VPM_SIGNALDIRS)) {
    02694     _thd.selend.x = x;
    02695     _thd.selend.y = y;
    02696     CalcRaildirsDrawstyle(x, y, method);
    02697     return;
    02698   }
    02699
    02700   /* Needed so level-land is placed correctly */
    02701   if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_POINT) {
    02702     x += TILE_SIZE / 2;
    02703     y += TILE_SIZE / 2;
    02704   }
    02705
    02706   sx = _thd.selstart.x;
    02707   sy = _thd.selstart.y;
    02708
    02709   int limit = 0;
    02710
    02711   switch (method) {
    02712     case VPM_X_OR_Y: // drag in X or Y direction
    02713       if (abs(sy - y) < abs(sx - x)) {
    02714         y = sy;
    02715         style = HT_DIR_X;
    02716       } else {
    02717         x = sx;
    02718         style = HT_DIR_Y;
    02719       }
    02720       goto calc_heightdiff_single_direction;
    02721
    02722     case VPM_X_LIMITED: // Drag in X direction (limited size).
    02723       limit = (_thd.sizelimit - 1) * TILE_SIZE;
    02724       /* FALL THROUGH */
    02725
    02726     case VPM_FIX_X: // drag in Y direction
    02727       x = sx;
    02728       style = HT_DIR_Y;
    02729       goto calc_heightdiff_single_direction;
    02730
    02731     case VPM_Y_LIMITED: // Drag in Y direction (limited size).
    02732       limit = (_thd.sizelimit - 1) * TILE_SIZE;
    02733       /* FALL THROUGH */
    02734
    02735     case VPM_FIX_Y: // drag in X direction
    02736       y = sy;
    02737       style = HT_DIR_X;
    02738
    02739 calc_heightdiff_single_direction:;
    02740       if (limit > 0) {
    02741         x = sx + Clamp(x - sx, -limit, limit);
    02742         y = sy + Clamp(y - sy, -limit, limit);
    02743       }
    02744       if (_settings_client.gui.measure_tooltip) {
    02745         TileIndex t0 = TileVirtXY(sx, sy);
    02746         TileIndex t1 = TileVirtXY(x, y);
    02747         uint distance = DistanceManhattan(t0, t1) + 1;
    02748         byte index = 0;
    02749         uint64 params[2];
    02750
    02751         if (distance != 1) {
    02752           /* With current code passing a HT_LINE style to calculate the height
    02753            * difference is enough. However if/when a point-tool is created
    02754            * with this method, function should be called with new_style (below)
    02755            * instead of HT_LINE | style case HT_POINT is handled specially
    02756            * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
    02757           int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
    02758
    02759           params[index++] = distance;
    02760           if (heightdiff != 0) params[index++] = heightdiff;
    02761         }
    02762
    02763         ShowMeasurementTooltips(measure_strings_length[index], index, params);
    02764       }
    02765       break;
    02766
    02767     case VPM_X_AND_Y_LIMITED: // Drag an X by Y constrained rect area.
    02768       limit = (_thd.sizelimit - 1) * TILE_SIZE;
    02769       x = sx + Clamp(x - sx, -limit, limit);
    02770       y = sy + Clamp(y - sy, -limit, limit);
    02771       /* FALL THROUGH */
    02772
    02773     case VPM_X_AND_Y: // drag an X by Y area
    02774       if (_settings_client.gui.measure_tooltip) {
    02775         static const StringID measure_strings_area[] = {
    02776           STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
    02777         };
    02778
    02779         TileIndex t0 = TileVirtXY(sx, sy);
    02780         TileIndex t1 = TileVirtXY(x, y);
    02781         uint dx = Delta(TileX(t0), TileX(t1)) + 1;
    02782         uint dy = Delta(TileY(t0), TileY(t1)) + 1;
    02783         byte index = 0;
    02784         uint64 params[3];
    02785
    02786         /* If dragging an area (eg dynamite tool) and it is actually a single
    02787          * row/column, change the type to 'line' to get proper calculation for height */
    02788         style = (HighLightStyle)_thd.next_drawstyle;
    02789         if (_thd.IsDraggingDiagonal()) {
    02790           /* Determine the "area" of the diagonal dragged selection.
    02791            * We assume the area is the number of tiles along the X
    02792            * edge and the number of tiles along the Y edge. However,
    02793            * multiplying these two numbers does not give the exact
    02794            * number of tiles; basically we are counting the black
    02795            * squares on a chess board and ignore the white ones to
    02796            * make the tile counts at the edges match up. There is no
    02797            * other way to make a proper count though.
    02798            *
    02799            * First convert to the rotated coordinate system. */
    02800           int dist_x = TileX(t0) - TileX(t1);
    02801           int dist_y = TileY(t0) - TileY(t1);
    02802           int a_max = dist_x + dist_y;
    02803           int b_max = dist_y - dist_x;
    02804
    02805           /* Now determine the size along the edge, but due to the
    02806            * chess board principle this counts double. */
    02807           a_max = abs(a_max + (a_max > 0 ? 2 : -2)) / 2;
    02808           b_max = abs(b_max + (b_max > 0 ? 2 : -2)) / 2;
    02809
    02810           /* We get a 1x1 on normal 2x1 rectangles, due to it being
    02811            * a seen as two sides. As the result for actual building
    02812            * will be the same as non-diagonal dragging revert to that
    02813            * behaviour to give it a more normally looking size. */
    02814           if (a_max != 1 || b_max != 1) {
    02815             dx = a_max;
    02816             dy = b_max;
    02817           }
    02818         } else if (style & HT_RECT) {
    02819           if (dx == 1) {
    02820             style = HT_LINE | HT_DIR_Y;
    02821           } else if (dy == 1) {
    02822             style = HT_LINE | HT_DIR_X;
    02823           }
    02824         }
    02825
    02826         if (t0 != 1 || t1 != 1) {
    02827           int heightdiff = CalcHeightdiff(style, 0, t0, t1);
    02828
    02829           params[index++] = dx;
    02830           params[index++] = dy;
    02831           if (heightdiff != 0) params[index++] = heightdiff;
    02832         }
    02833
    02834         ShowMeasurementTooltips(measure_strings_area[index], index, params);
    02835       }
    02836       break;
    02837
    02838     default: NOT_REACHED();
    02839   }
    02840
    02841   _thd.selend.x = x;
    02842   _thd.selend.y = y;
    02843 }
    02844
    02849 EventState VpHandlePlaceSizingDrag()
    02850 {
    02851   if (_special_mouse_mode != WSM_SIZING) return ES_NOT_HANDLED;
    02852
    02853   /* stop drag mode if the window has been closed */
    02854   Window *w = _thd.GetCallbackWnd();
    02855   if (w == NULL) {
    02856     ResetObjectToPlace();
    02857     return ES_HANDLED;
    02858   }
    02859
    02860   /* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
    02861   if (_left_button_down) {
    02862     w->OnPlaceDrag(_thd.select_method, _thd.select_proc, GetTileBelowCursor());
    02863     return ES_HANDLED;
    02864   }
    02865
    02866   /* mouse button released..
    02867    * keep the selected tool, but reset it to the original mode. */
    02868   _special_mouse_mode = WSM_NONE;
    02869   HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
    02870   if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_RECT) {
    02871     _thd.place_mode = HT_RECT | others;
    02872   } else if (_thd.select_method & VPM_SIGNALDIRS) {
    02873     _thd.place_mode = HT_RECT | others;
    02874   } else if (_thd.select_method & VPM_RAILDIRS) {
    02875     _thd.place_mode = (_thd.select_method & ~VPM_RAILDIRS) ? _thd.next_drawstyle : (HT_RAIL | others);
    02876   } else {
    02877     _thd.place_mode = HT_POINT | others;
    02878   }
    02879   SetTileSelectSize(1, 1);
    02880
    02881   w->OnPlaceMouseUp(_thd.select_method, _thd.select_proc, _thd.selend, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y));
    02882
    02883   return ES_HANDLED;
    02884 }
    02885
    02886 void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
    02887 {
    02888   SetObjectToPlace(icon, pal, mode, w->window_class, w->window_number);
    02889 }
    02890
    02891 #include "table/animcursors.h"
    02892
    02893 void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
    02894 {
    02895   if (_thd.window_class != WC_INVALID) {
    02896     /* Undo clicking on button and drag & drop */
    02897     Window *w = _thd.GetCallbackWnd();
    02898     /* Call the abort function, but set the window class to something
    02899      * that will never be used to avoid infinite loops. Setting it to
    02900      * the 'next' window class must not be done because recursion into
    02901      * this function might in some cases reset the newly set object to
    02902      * place or not properly reset the original selection. */
    02903     _thd.window_class = WC_INVALID;
    02904     if (w != NULL) w->OnPlaceObjectAbort();
    02905   }
    02906
    02907   SetTileSelectSize(1, 1);
    02908
    02909   _thd.make_square_red = false;
    02910
    02911   if (mode == HT_DRAG) { // HT_DRAG is for dragdropping trains in the depot window
    02912     mode = HT_NONE;
    02913     _special_mouse_mode = WSM_DRAGDROP;
    02914   } else {
    02915     _special_mouse_mode = WSM_NONE;
    02916   }
    02917
    02918   _thd.place_mode = mode;
    02919   _thd.window_class = window_class;
    02920   _thd.window_number = window_num;
    02921
    02922   if ((mode & HT_DRAG_MASK) == HT_SPECIAL) { // special tools, like tunnels or docks start with presizing mode
    02923     VpStartPreSizing();
    02924   }
    02925
    02926   if ((icon & ANIMCURSOR_FLAG) != 0) {
    02927     SetAnimatedMouseCursor(_animcursors[icon & ~ANIMCURSOR_FLAG]);
    02928   } else {
    02929     SetMouseCursor(icon, pal);
    02930   }
    02931
    02932 }
    02933
    02934 void ResetObjectToPlace()
    02935 {
    02936   SetObjectToPlace(SPR_CURSOR_MOUSE, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
    02937 }