viewport.cpp

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