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