Fix #9020: Update station coverage highlight when adding/removing tiles
[openttd-github.git] / src / viewport.cpp
blob3819266c54bc425f5c4f4775b83b3f32fd0fe0cd
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /**
9 * @file viewport.cpp Handling of all viewports.
11 * \verbatim
12 * The in-game coordinate system looks like this *
13 * *
14 * ^ Z *
15 * | *
16 * | *
17 * | *
18 * | *
19 * / \ *
20 * / \ *
21 * / \ *
22 * / \ *
23 * X < > Y *
24 * \endverbatim
27 /**
28 * @defgroup vp_column_row Rows and columns in the viewport
30 * Columns are vertical sections of the viewport that are half a tile wide.
31 * The origin, i.e. column 0, is through the northern and southern most tile.
32 * This means that the column of e.g. Tile(0, 0) and Tile(100, 100) are in
33 * column number 0. The negative columns are towards the left of the screen,
34 * or towards the west, whereas the positive ones are towards respectively
35 * the right and east.
36 * With half a tile wide is meant that the next column of tiles directly west
37 * or east of the centre line are respectively column -1 and 1. Their tile
38 * centers are only half a tile from the center of their adjoining tile when
39 * looking only at the X-coordinate.
41 * \verbatim
42 * ╳ *
43 * ╱ ╲ *
44 * ╳ 0 ╳ *
45 * ╱ ╲ ╱ ╲ *
46 * ╳-1 ╳ 1 ╳ *
47 * ╱ ╲ ╱ ╲ ╱ ╲ *
48 * ╳-2 ╳ 0 ╳ 2 ╳ *
49 * ╲ ╱ ╲ ╱ ╲ ╱ *
50 * ╳-1 ╳ 1 ╳ *
51 * ╲ ╱ ╲ ╱ *
52 * ╳ 0 ╳ *
53 * ╲ ╱ *
54 * ╳ *
55 * \endverbatim
58 * Rows are horizontal sections of the viewport, also half a tile wide.
59 * This time the northern most tile on the map defines 0 and
60 * everything south of that has a positive number.
63 #include "stdafx.h"
64 #include "landscape.h"
65 #include "viewport_func.h"
66 #include "station_base.h"
67 #include "waypoint_base.h"
68 #include "town.h"
69 #include "signs_base.h"
70 #include "signs_func.h"
71 #include "vehicle_base.h"
72 #include "vehicle_gui.h"
73 #include "blitter/factory.hpp"
74 #include "strings_func.h"
75 #include "zoom_func.h"
76 #include "vehicle_func.h"
77 #include "company_func.h"
78 #include "waypoint_func.h"
79 #include "window_func.h"
80 #include "tilehighlight_func.h"
81 #include "window_gui.h"
82 #include "linkgraph/linkgraph_gui.h"
83 #include "viewport_kdtree.h"
84 #include "town_kdtree.h"
85 #include "viewport_sprite_sorter.h"
86 #include "bridge_map.h"
87 #include "company_base.h"
88 #include "command_func.h"
89 #include "network/network_func.h"
90 #include "framerate_type.h"
91 #include "viewport_cmd.h"
93 #include <forward_list>
94 #include <map>
95 #include <stack>
97 #include "table/strings.h"
98 #include "table/string_colours.h"
100 #include "safeguards.h"
102 Point _tile_fract_coords;
105 ViewportSignKdtree _viewport_sign_kdtree(&Kdtree_ViewportSignXYFunc);
106 static int _viewport_sign_maxwidth = 0;
109 static const int MAX_TILE_EXTENT_LEFT = ZOOM_LVL_BASE * TILE_PIXELS; ///< Maximum left extent of tile relative to north corner.
110 static const int MAX_TILE_EXTENT_RIGHT = ZOOM_LVL_BASE * TILE_PIXELS; ///< Maximum right extent of tile relative to north corner.
111 static const int MAX_TILE_EXTENT_TOP = ZOOM_LVL_BASE * MAX_BUILDING_PIXELS; ///< Maximum top extent of tile relative to north corner (not considering bridges).
112 static const int MAX_TILE_EXTENT_BOTTOM = ZOOM_LVL_BASE * (TILE_PIXELS + 2 * TILE_HEIGHT); ///< Maximum bottom extent of tile relative to north corner (worst case: #SLOPE_STEEP_N).
114 struct StringSpriteToDraw {
115 StringID string;
116 Colours colour;
117 int32 x;
118 int32 y;
119 uint64 params[2];
120 uint16 width;
123 struct TileSpriteToDraw {
124 SpriteID image;
125 PaletteID pal;
126 const SubSprite *sub; ///< only draw a rectangular part of the sprite
127 int32 x; ///< screen X coordinate of sprite
128 int32 y; ///< screen Y coordinate of sprite
131 struct ChildScreenSpriteToDraw {
132 SpriteID image;
133 PaletteID pal;
134 const SubSprite *sub; ///< only draw a rectangular part of the sprite
135 int32 x;
136 int32 y;
137 int next; ///< next child to draw (-1 at the end)
140 /** Enumeration of multi-part foundations */
141 enum FoundationPart {
142 FOUNDATION_PART_NONE = 0xFF, ///< Neither foundation nor groundsprite drawn yet.
143 FOUNDATION_PART_NORMAL = 0, ///< First part (normal foundation or no foundation)
144 FOUNDATION_PART_HALFTILE = 1, ///< Second part (halftile foundation)
145 FOUNDATION_PART_END
149 * Mode of "sprite combining"
150 * @see StartSpriteCombine
152 enum SpriteCombineMode {
153 SPRITE_COMBINE_NONE, ///< Every #AddSortableSpriteToDraw start its own bounding box
154 SPRITE_COMBINE_PENDING, ///< %Sprite combining will start with the next unclipped sprite.
155 SPRITE_COMBINE_ACTIVE, ///< %Sprite combining is active. #AddSortableSpriteToDraw outputs child sprites.
158 typedef std::vector<TileSpriteToDraw> TileSpriteToDrawVector;
159 typedef std::vector<StringSpriteToDraw> StringSpriteToDrawVector;
160 typedef std::vector<ParentSpriteToDraw> ParentSpriteToDrawVector;
161 typedef std::vector<ChildScreenSpriteToDraw> ChildScreenSpriteToDrawVector;
163 /** Data structure storing rendering information */
164 struct ViewportDrawer {
165 DrawPixelInfo dpi;
167 StringSpriteToDrawVector string_sprites_to_draw;
168 TileSpriteToDrawVector tile_sprites_to_draw;
169 ParentSpriteToDrawVector parent_sprites_to_draw;
170 ParentSpriteToSortVector parent_sprites_to_sort; ///< Parent sprite pointer array used for sorting
171 ChildScreenSpriteToDrawVector child_screen_sprites_to_draw;
173 int *last_child;
175 SpriteCombineMode combine_sprites; ///< Current mode of "sprite combining". @see StartSpriteCombine
177 int foundation[FOUNDATION_PART_END]; ///< Foundation sprites (index into parent_sprites_to_draw).
178 FoundationPart foundation_part; ///< Currently active foundation for ground sprite drawing.
179 int *last_foundation_child[FOUNDATION_PART_END]; ///< Tail of ChildSprite list of the foundations. (index into child_screen_sprites_to_draw)
180 Point foundation_offset[FOUNDATION_PART_END]; ///< Pixel offset for ground sprites on the foundations.
183 static bool MarkViewportDirty(const Viewport *vp, int left, int top, int right, int bottom);
185 static ViewportDrawer _vd;
187 TileHighlightData _thd;
188 static TileInfo *_cur_ti;
189 bool _draw_bounding_boxes = false;
190 bool _draw_dirty_blocks = false;
191 uint _dirty_block_colour = 0;
192 static VpSpriteSorter _vp_sprite_sorter = nullptr;
194 static Point MapXYZToViewport(const Viewport *vp, int x, int y, int z)
196 Point p = RemapCoords(x, y, z);
197 p.x -= vp->virtual_width / 2;
198 p.y -= vp->virtual_height / 2;
199 return p;
202 void DeleteWindowViewport(Window *w)
204 if (w->viewport == nullptr) return;
206 delete w->viewport->overlay;
207 free(w->viewport);
208 w->viewport = nullptr;
212 * Initialize viewport of the window for use.
213 * @param w Window to use/display the viewport in
214 * @param x Offset of left edge of viewport with respect to left edge window \a w
215 * @param y Offset of top edge of viewport with respect to top edge window \a w
216 * @param width Width of the viewport
217 * @param height Height of the viewport
218 * @param follow_flags Flags controlling the viewport.
219 * - If bit 31 is set, the lower 20 bits are the vehicle that the viewport should follow.
220 * - If bit 31 is clear, it is a #TileIndex.
221 * @param zoom Zoomlevel to display
223 void InitializeWindowViewport(Window *w, int x, int y,
224 int width, int height, uint32 follow_flags, ZoomLevel zoom)
226 assert(w->viewport == nullptr);
228 ViewportData *vp = CallocT<ViewportData>(1);
230 vp->left = x + w->left;
231 vp->top = y + w->top;
232 vp->width = width;
233 vp->height = height;
235 vp->zoom = static_cast<ZoomLevel>(Clamp(zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max));
237 vp->virtual_width = ScaleByZoom(width, zoom);
238 vp->virtual_height = ScaleByZoom(height, zoom);
240 Point pt;
242 if (follow_flags & 0x80000000) {
243 const Vehicle *veh;
245 vp->follow_vehicle = (VehicleID)(follow_flags & 0xFFFFF);
246 veh = Vehicle::Get(vp->follow_vehicle);
247 pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
248 } else {
249 x = TileX(follow_flags) * TILE_SIZE;
250 y = TileY(follow_flags) * TILE_SIZE;
252 vp->follow_vehicle = INVALID_VEHICLE;
253 pt = MapXYZToViewport(vp, x, y, GetSlopePixelZ(x, y));
256 vp->scrollpos_x = pt.x;
257 vp->scrollpos_y = pt.y;
258 vp->dest_scrollpos_x = pt.x;
259 vp->dest_scrollpos_y = pt.y;
261 vp->overlay = nullptr;
263 w->viewport = vp;
264 vp->virtual_left = 0; // pt.x;
265 vp->virtual_top = 0; // pt.y;
268 static Point _vp_move_offs;
270 static void DoSetViewportPosition(Window::IteratorToFront it, int left, int top, int width, int height)
272 for (; !it.IsEnd(); ++it) {
273 const Window *w = *it;
274 if (left + width > w->left &&
275 w->left + w->width > left &&
276 top + height > w->top &&
277 w->top + w->height > top) {
279 if (left < w->left) {
280 DoSetViewportPosition(it, left, top, w->left - left, height);
281 DoSetViewportPosition(it, left + (w->left - left), top, width - (w->left - left), height);
282 return;
285 if (left + width > w->left + w->width) {
286 DoSetViewportPosition(it, left, top, (w->left + w->width - left), height);
287 DoSetViewportPosition(it, left + (w->left + w->width - left), top, width - (w->left + w->width - left), height);
288 return;
291 if (top < w->top) {
292 DoSetViewportPosition(it, left, top, width, (w->top - top));
293 DoSetViewportPosition(it, left, top + (w->top - top), width, height - (w->top - top));
294 return;
297 if (top + height > w->top + w->height) {
298 DoSetViewportPosition(it, left, top, width, (w->top + w->height - top));
299 DoSetViewportPosition(it, left, top + (w->top + w->height - top), width, height - (w->top + w->height - top));
300 return;
303 return;
308 int xo = _vp_move_offs.x;
309 int yo = _vp_move_offs.y;
311 if (abs(xo) >= width || abs(yo) >= height) {
312 /* fully_outside */
313 RedrawScreenRect(left, top, left + width, top + height);
314 return;
317 GfxScroll(left, top, width, height, xo, yo);
319 if (xo > 0) {
320 RedrawScreenRect(left, top, xo + left, top + height);
321 left += xo;
322 width -= xo;
323 } else if (xo < 0) {
324 RedrawScreenRect(left + width + xo, top, left + width, top + height);
325 width += xo;
328 if (yo > 0) {
329 RedrawScreenRect(left, top, width + left, top + yo);
330 } else if (yo < 0) {
331 RedrawScreenRect(left, top + height + yo, width + left, top + height);
336 static void SetViewportPosition(Window *w, int x, int y)
338 Viewport *vp = w->viewport;
339 int old_left = vp->virtual_left;
340 int old_top = vp->virtual_top;
341 int i;
342 int left, top, width, height;
344 vp->virtual_left = x;
345 vp->virtual_top = y;
347 /* Viewport is bound to its left top corner, so it must be rounded down (UnScaleByZoomLower)
348 * else glitch described in FS#1412 will happen (offset by 1 pixel with zoom level > NORMAL)
350 old_left = UnScaleByZoomLower(old_left, vp->zoom);
351 old_top = UnScaleByZoomLower(old_top, vp->zoom);
352 x = UnScaleByZoomLower(x, vp->zoom);
353 y = UnScaleByZoomLower(y, vp->zoom);
355 old_left -= x;
356 old_top -= y;
358 if (old_top == 0 && old_left == 0) return;
360 _vp_move_offs.x = old_left;
361 _vp_move_offs.y = old_top;
363 left = vp->left;
364 top = vp->top;
365 width = vp->width;
366 height = vp->height;
368 if (left < 0) {
369 width += left;
370 left = 0;
373 i = left + width - _screen.width;
374 if (i >= 0) width -= i;
376 if (width > 0) {
377 if (top < 0) {
378 height += top;
379 top = 0;
382 i = top + height - _screen.height;
383 if (i >= 0) height -= i;
385 if (height > 0) {
386 Window::IteratorToFront it(w);
387 ++it;
388 DoSetViewportPosition(it, left, top, width, height);
394 * Is a xy position inside the viewport of the window?
395 * @param w Window to examine its viewport
396 * @param x X coordinate of the xy position
397 * @param y Y coordinate of the xy position
398 * @return Pointer to the viewport if the xy position is in the viewport of the window,
399 * otherwise \c nullptr is returned.
401 Viewport *IsPtInWindowViewport(const Window *w, int x, int y)
403 Viewport *vp = w->viewport;
405 if (vp != nullptr &&
406 IsInsideMM(x, vp->left, vp->left + vp->width) &&
407 IsInsideMM(y, vp->top, vp->top + vp->height))
408 return vp;
410 return nullptr;
414 * Translate screen coordinate in a viewport to underlying tile coordinate.
416 * Returns exact point of the map that is visible in the given place
417 * of the viewport (3D perspective), height of tiles and foundations matter.
419 * @param vp Viewport that contains the (\a x, \a y) screen coordinate
420 * @param x Screen x coordinate, distance in pixels from the left edge of viewport frame
421 * @param y Screen y coordinate, distance in pixels from the top edge of viewport frame
422 * @param clamp_to_map Clamp the coordinate outside of the map to the closest, non-void tile within the map
423 * @return Tile coordinate or (-1, -1) if given x or y is not within viewport frame
425 Point TranslateXYToTileCoord(const Viewport *vp, int x, int y, bool clamp_to_map)
427 if (!IsInsideBS(x, vp->left, vp->width) || !IsInsideBS(y, vp->top, vp->height)) {
428 Point pt = { -1, -1 };
429 return pt;
432 return InverseRemapCoords2(
433 ScaleByZoom(x - vp->left, vp->zoom) + vp->virtual_left,
434 ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top, clamp_to_map);
437 /* When used for zooming, check area below current coordinates (x,y)
438 * and return the tile of the zoomed out/in position (zoom_x, zoom_y)
439 * when you just want the tile, make x = zoom_x and y = zoom_y */
440 static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
442 Window *w;
443 Viewport *vp;
444 Point pt;
446 if ( (w = FindWindowFromPt(x, y)) != nullptr &&
447 (vp = IsPtInWindowViewport(w, x, y)) != nullptr)
448 return TranslateXYToTileCoord(vp, zoom_x, zoom_y);
450 pt.y = pt.x = -1;
451 return pt;
454 Point GetTileBelowCursor()
456 return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, _cursor.pos.x, _cursor.pos.y);
460 Point GetTileZoomCenterWindow(bool in, Window * w)
462 int x, y;
463 Viewport *vp = w->viewport;
465 if (in) {
466 x = ((_cursor.pos.x - vp->left) >> 1) + (vp->width >> 2);
467 y = ((_cursor.pos.y - vp->top) >> 1) + (vp->height >> 2);
468 } else {
469 x = vp->width - (_cursor.pos.x - vp->left);
470 y = vp->height - (_cursor.pos.y - vp->top);
472 /* Get the tile below the cursor and center on the zoomed-out center */
473 return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, x + vp->left, y + vp->top);
477 * Update the status of the zoom-buttons according to the zoom-level
478 * of the viewport. This will update their status and invalidate accordingly
479 * @param w Window pointer to the window that has the zoom buttons
480 * @param vp pointer to the viewport whose zoom-level the buttons represent
481 * @param widget_zoom_in widget index for window with zoom-in button
482 * @param widget_zoom_out widget index for window with zoom-out button
484 void HandleZoomMessage(Window *w, const Viewport *vp, byte widget_zoom_in, byte widget_zoom_out)
486 w->SetWidgetDisabledState(widget_zoom_in, vp->zoom <= _settings_client.gui.zoom_min);
487 w->SetWidgetDirty(widget_zoom_in);
489 w->SetWidgetDisabledState(widget_zoom_out, vp->zoom >= _settings_client.gui.zoom_max);
490 w->SetWidgetDirty(widget_zoom_out);
494 * Schedules a tile sprite for drawing.
496 * @param image the image to draw.
497 * @param pal the provided palette.
498 * @param x position x (world coordinates) of the sprite.
499 * @param y position y (world coordinates) of the sprite.
500 * @param z position z (world coordinates) of the sprite.
501 * @param sub Only draw a part of the sprite.
502 * @param extra_offs_x Pixel X offset for the sprite position.
503 * @param extra_offs_y Pixel Y offset for the sprite position.
505 static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub = nullptr, int extra_offs_x = 0, int extra_offs_y = 0)
507 assert((image & SPRITE_MASK) < MAX_SPRITES);
509 TileSpriteToDraw &ts = _vd.tile_sprites_to_draw.emplace_back();
510 ts.image = image;
511 ts.pal = pal;
512 ts.sub = sub;
513 Point pt = RemapCoords(x, y, z);
514 ts.x = pt.x + extra_offs_x;
515 ts.y = pt.y + extra_offs_y;
519 * Adds a child sprite to the active foundation.
521 * The pixel offset of the sprite relative to the ParentSprite is the sum of the offset passed to OffsetGroundSprite() and extra_offs_?.
523 * @param image the image to draw.
524 * @param pal the provided palette.
525 * @param sub Only draw a part of the sprite.
526 * @param foundation_part Foundation part.
527 * @param extra_offs_x Pixel X offset for the sprite position.
528 * @param extra_offs_y Pixel Y offset for the sprite position.
530 static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
532 assert(IsInsideMM(foundation_part, 0, FOUNDATION_PART_END));
533 assert(_vd.foundation[foundation_part] != -1);
534 Point offs = _vd.foundation_offset[foundation_part];
536 /* Change the active ChildSprite list to the one of the foundation */
537 int *old_child = _vd.last_child;
538 _vd.last_child = _vd.last_foundation_child[foundation_part];
540 AddChildSpriteScreen(image, pal, offs.x + extra_offs_x, offs.y + extra_offs_y, false, sub, false);
542 /* Switch back to last ChildSprite list */
543 _vd.last_child = old_child;
547 * Draws a ground sprite at a specific world-coordinate relative to the current tile.
548 * If the current tile is drawn on top of a foundation the sprite is added as child sprite to the "foundation"-ParentSprite.
550 * @param image the image to draw.
551 * @param pal the provided palette.
552 * @param x position x (world coordinates) of the sprite relative to current tile.
553 * @param y position y (world coordinates) of the sprite relative to current tile.
554 * @param z position z (world coordinates) of the sprite relative to current tile.
555 * @param sub Only draw a part of the sprite.
556 * @param extra_offs_x Pixel X offset for the sprite position.
557 * @param extra_offs_y Pixel Y offset for the sprite position.
559 void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
561 /* Switch to first foundation part, if no foundation was drawn */
562 if (_vd.foundation_part == FOUNDATION_PART_NONE) _vd.foundation_part = FOUNDATION_PART_NORMAL;
564 if (_vd.foundation[_vd.foundation_part] != -1) {
565 Point pt = RemapCoords(x, y, z);
566 AddChildSpriteToFoundation(image, pal, sub, _vd.foundation_part, pt.x + extra_offs_x * ZOOM_LVL_BASE, pt.y + extra_offs_y * ZOOM_LVL_BASE);
567 } else {
568 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);
573 * Draws a ground sprite for the current tile.
574 * If the current tile is drawn on top of a foundation the sprite is added as child sprite to the "foundation"-ParentSprite.
576 * @param image the image to draw.
577 * @param pal the provided palette.
578 * @param sub Only draw a part of the sprite.
579 * @param extra_offs_x Pixel X offset for the sprite position.
580 * @param extra_offs_y Pixel Y offset for the sprite position.
582 void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
584 DrawGroundSpriteAt(image, pal, 0, 0, 0, sub, extra_offs_x, extra_offs_y);
588 * Called when a foundation has been drawn for the current tile.
589 * Successive ground sprites for the current tile will be drawn as child sprites of the "foundation"-ParentSprite, not as TileSprites.
591 * @param x sprite x-offset (screen coordinates) of ground sprites relative to the "foundation"-ParentSprite.
592 * @param y sprite y-offset (screen coordinates) of ground sprites relative to the "foundation"-ParentSprite.
594 void OffsetGroundSprite(int x, int y)
596 /* Switch to next foundation part */
597 switch (_vd.foundation_part) {
598 case FOUNDATION_PART_NONE:
599 _vd.foundation_part = FOUNDATION_PART_NORMAL;
600 break;
601 case FOUNDATION_PART_NORMAL:
602 _vd.foundation_part = FOUNDATION_PART_HALFTILE;
603 break;
604 default: NOT_REACHED();
607 /* _vd.last_child == nullptr if foundation sprite was clipped by the viewport bounds */
608 if (_vd.last_child != nullptr) _vd.foundation[_vd.foundation_part] = (uint)_vd.parent_sprites_to_draw.size() - 1;
610 _vd.foundation_offset[_vd.foundation_part].x = x * ZOOM_LVL_BASE;
611 _vd.foundation_offset[_vd.foundation_part].y = y * ZOOM_LVL_BASE;
612 _vd.last_foundation_child[_vd.foundation_part] = _vd.last_child;
616 * Adds a child sprite to a parent sprite.
617 * In contrast to "AddChildSpriteScreen()" the sprite position is in world coordinates
619 * @param image the image to draw.
620 * @param pal the provided palette.
621 * @param x position x of the sprite.
622 * @param y position y of the sprite.
623 * @param z position z of the sprite.
624 * @param sub Only draw a part of the sprite.
626 static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, int z, const SubSprite *sub)
628 Point pt = RemapCoords(x, y, z);
629 const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
631 if (pt.x + spr->x_offs >= _vd.dpi.left + _vd.dpi.width ||
632 pt.x + spr->x_offs + spr->width <= _vd.dpi.left ||
633 pt.y + spr->y_offs >= _vd.dpi.top + _vd.dpi.height ||
634 pt.y + spr->y_offs + spr->height <= _vd.dpi.top)
635 return;
637 const ParentSpriteToDraw &pstd = _vd.parent_sprites_to_draw.back();
638 AddChildSpriteScreen(image, pal, pt.x - pstd.left, pt.y - pstd.top, false, sub, false);
642 * Draw a (transparent) sprite at given coordinates with a given bounding box.
643 * The bounding box extends from (x + bb_offset_x, y + bb_offset_y, z + bb_offset_z) to (x + w - 1, y + h - 1, z + dz - 1), both corners included.
644 * Bounding boxes with bb_offset_x == w or bb_offset_y == h or bb_offset_z == dz are allowed and produce thin slices.
646 * @note Bounding boxes are normally specified with bb_offset_x = bb_offset_y = bb_offset_z = 0. The extent of the bounding box in negative direction is
647 * defined by the sprite offset in the grf file.
648 * However if modifying the sprite offsets is not suitable (e.g. when using existing graphics), the bounding box can be tuned by bb_offset.
650 * @pre w >= bb_offset_x, h >= bb_offset_y, dz >= bb_offset_z. Else w, h or dz are ignored.
652 * @param image the image to combine and draw,
653 * @param pal the provided palette,
654 * @param x position X (world) of the sprite,
655 * @param y position Y (world) of the sprite,
656 * @param w bounding box extent towards positive X (world),
657 * @param h bounding box extent towards positive Y (world),
658 * @param dz bounding box extent towards positive Z (world),
659 * @param z position Z (world) of the sprite,
660 * @param transparent if true, switch the palette between the provided palette and the transparent palette,
661 * @param bb_offset_x bounding box extent towards negative X (world),
662 * @param bb_offset_y bounding box extent towards negative Y (world),
663 * @param bb_offset_z bounding box extent towards negative Z (world)
664 * @param sub Only draw a part of the sprite.
666 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)
668 int32 left, right, top, bottom;
670 assert((image & SPRITE_MASK) < MAX_SPRITES);
672 /* make the sprites transparent with the right palette */
673 if (transparent) {
674 SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
675 pal = PALETTE_TO_TRANSPARENT;
678 if (_vd.combine_sprites == SPRITE_COMBINE_ACTIVE) {
679 AddCombinedSprite(image, pal, x, y, z, sub);
680 return;
683 _vd.last_child = nullptr;
685 Point pt = RemapCoords(x, y, z);
686 int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
688 /* Compute screen extents of sprite */
689 if (image == SPR_EMPTY_BOUNDING_BOX) {
690 left = tmp_left = RemapCoords(x + w , y + bb_offset_y, z + bb_offset_z).x;
691 right = RemapCoords(x + bb_offset_x, y + h , z + bb_offset_z).x + 1;
692 top = tmp_top = RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz ).y;
693 bottom = RemapCoords(x + w , y + h , z + bb_offset_z).y + 1;
694 } else {
695 const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
696 left = tmp_left = (pt.x += spr->x_offs);
697 right = (pt.x + spr->width );
698 top = tmp_top = (pt.y += spr->y_offs);
699 bottom = (pt.y + spr->height);
702 if (_draw_bounding_boxes && (image != SPR_EMPTY_BOUNDING_BOX)) {
703 /* Compute maximal extents of sprite and its bounding box */
704 left = std::min(left , RemapCoords(x + w , y + bb_offset_y, z + bb_offset_z).x);
705 right = std::max(right , RemapCoords(x + bb_offset_x, y + h , z + bb_offset_z).x + 1);
706 top = std::min(top , RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz ).y);
707 bottom = std::max(bottom, RemapCoords(x + w , y + h , z + bb_offset_z).y + 1);
710 /* Do not add the sprite to the viewport, if it is outside */
711 if (left >= _vd.dpi.left + _vd.dpi.width ||
712 right <= _vd.dpi.left ||
713 top >= _vd.dpi.top + _vd.dpi.height ||
714 bottom <= _vd.dpi.top) {
715 return;
718 ParentSpriteToDraw &ps = _vd.parent_sprites_to_draw.emplace_back();
719 ps.x = tmp_x;
720 ps.y = tmp_y;
722 ps.left = tmp_left;
723 ps.top = tmp_top;
725 ps.image = image;
726 ps.pal = pal;
727 ps.sub = sub;
728 ps.xmin = x + bb_offset_x;
729 ps.xmax = x + std::max(bb_offset_x, w) - 1;
731 ps.ymin = y + bb_offset_y;
732 ps.ymax = y + std::max(bb_offset_y, h) - 1;
734 ps.zmin = z + bb_offset_z;
735 ps.zmax = z + std::max(bb_offset_z, dz) - 1;
737 ps.first_child = -1;
739 _vd.last_child = &ps.first_child;
741 if (_vd.combine_sprites == SPRITE_COMBINE_PENDING) _vd.combine_sprites = SPRITE_COMBINE_ACTIVE;
745 * Starts a block of sprites, which are "combined" into a single bounding box.
747 * Subsequent calls to #AddSortableSpriteToDraw will be drawn into the same bounding box.
748 * That is: The first sprite that is not clipped by the viewport defines the bounding box, and
749 * the following sprites will be child sprites to that one.
751 * That implies:
752 * - The drawing order is definite. No other sprites will be sorted between those of the block.
753 * - You have to provide a valid bounding box for all sprites,
754 * as you won't know which one is the first non-clipped one.
755 * Preferable you use the same bounding box for all.
756 * - You cannot use #AddChildSpriteScreen inside the block, as its result will be indefinite.
758 * The block is terminated by #EndSpriteCombine.
760 * You cannot nest "combined" blocks.
762 void StartSpriteCombine()
764 assert(_vd.combine_sprites == SPRITE_COMBINE_NONE);
765 _vd.combine_sprites = SPRITE_COMBINE_PENDING;
769 * Terminates a block of sprites started by #StartSpriteCombine.
770 * Take a look there for details.
772 void EndSpriteCombine()
774 assert(_vd.combine_sprites != SPRITE_COMBINE_NONE);
775 _vd.combine_sprites = SPRITE_COMBINE_NONE;
779 * Check if the parameter "check" is inside the interval between
780 * begin and end, including both begin and end.
781 * @note Whether \c begin or \c end is the biggest does not matter.
782 * This method will account for that.
783 * @param begin The begin of the interval.
784 * @param end The end of the interval.
785 * @param check The value to check.
787 static bool IsInRangeInclusive(int begin, int end, int check)
789 if (begin > end) Swap(begin, end);
790 return begin <= check && check <= end;
794 * Checks whether a point is inside the selected a diagonal rectangle given by _thd.size and _thd.pos
795 * @param x The x coordinate of the point to be checked.
796 * @param y The y coordinate of the point to be checked.
797 * @return True if the point is inside the rectangle, else false.
799 bool IsInsideRotatedRectangle(int x, int y)
801 int dist_a = (_thd.size.x + _thd.size.y); // Rotated coordinate system for selected rectangle.
802 int dist_b = (_thd.size.x - _thd.size.y); // We don't have to divide by 2. It's all relative!
803 int a = ((x - _thd.pos.x) + (y - _thd.pos.y)); // Rotated coordinate system for the point under scrutiny.
804 int b = ((x - _thd.pos.x) - (y - _thd.pos.y));
806 /* Check if a and b are between 0 and dist_a or dist_b respectively. */
807 return IsInRangeInclusive(dist_a, 0, a) && IsInRangeInclusive(dist_b, 0, b);
811 * Add a child sprite to a parent sprite.
813 * @param image the image to draw.
814 * @param pal the provided palette.
815 * @param x sprite x-offset (screen coordinates) relative to parent sprite.
816 * @param y sprite y-offset (screen coordinates) relative to parent sprite.
817 * @param transparent if true, switch the palette between the provided palette and the transparent palette,
818 * @param sub Only draw a part of the sprite.
820 void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale)
822 assert((image & SPRITE_MASK) < MAX_SPRITES);
824 /* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
825 if (_vd.last_child == nullptr) return;
827 /* make the sprites transparent with the right palette */
828 if (transparent) {
829 SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
830 pal = PALETTE_TO_TRANSPARENT;
833 *_vd.last_child = (uint)_vd.child_screen_sprites_to_draw.size();
835 ChildScreenSpriteToDraw &cs = _vd.child_screen_sprites_to_draw.emplace_back();
836 cs.image = image;
837 cs.pal = pal;
838 cs.sub = sub;
839 cs.x = scale ? x * ZOOM_LVL_BASE : x;
840 cs.y = scale ? y * ZOOM_LVL_BASE : y;
841 cs.next = -1;
843 /* Append the sprite to the active ChildSprite list.
844 * If the active ParentSprite is a foundation, update last_foundation_child as well.
845 * Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
846 if (_vd.last_foundation_child[0] == _vd.last_child) _vd.last_foundation_child[0] = &cs.next;
847 if (_vd.last_foundation_child[1] == _vd.last_child) _vd.last_foundation_child[1] = &cs.next;
848 _vd.last_child = &cs.next;
851 static void AddStringToDraw(int x, int y, StringID string, uint64 params_1, uint64 params_2, Colours colour, uint16 width)
853 assert(width != 0);
854 StringSpriteToDraw &ss = _vd.string_sprites_to_draw.emplace_back();
855 ss.string = string;
856 ss.x = x;
857 ss.y = y;
858 ss.params[0] = params_1;
859 ss.params[1] = params_2;
860 ss.width = width;
861 ss.colour = colour;
866 * Draws sprites between ground sprite and everything above.
868 * The sprite is either drawn as TileSprite or as ChildSprite of the active foundation.
870 * @param image the image to draw.
871 * @param pal the provided palette.
872 * @param ti TileInfo Tile that is being drawn
873 * @param z_offset Z offset relative to the groundsprite. Only used for the sprite position, not for sprite sorting.
874 * @param foundation_part Foundation part the sprite belongs to.
876 static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part)
878 /* FIXME: This is not totally valid for some autorail highlights that extend over the edges of the tile. */
879 if (_vd.foundation[foundation_part] == -1) {
880 /* draw on real ground */
881 AddTileSpriteToDraw(image, pal, ti->x, ti->y, ti->z + z_offset);
882 } else {
883 /* draw on top of foundation */
884 AddChildSpriteToFoundation(image, pal, nullptr, foundation_part, 0, -z_offset * ZOOM_LVL_BASE);
889 * Draws a selection rectangle on a tile.
891 * @param ti TileInfo Tile that is being drawn
892 * @param pal Palette to apply.
894 static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
896 if (!IsValidTile(ti->tile)) return;
898 SpriteID sel;
899 if (IsHalftileSlope(ti->tileh)) {
900 Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
901 SpriteID sel2 = SPR_HALFTILE_SELECTION_FLAT + halftile_corner;
902 DrawSelectionSprite(sel2, pal, ti, 7 + TILE_HEIGHT, FOUNDATION_PART_HALFTILE);
904 Corner opposite_corner = OppositeCorner(halftile_corner);
905 if (IsSteepSlope(ti->tileh)) {
906 sel = SPR_HALFTILE_SELECTION_DOWN;
907 } else {
908 sel = ((ti->tileh & SlopeWithOneCornerRaised(opposite_corner)) != 0 ? SPR_HALFTILE_SELECTION_UP : SPR_HALFTILE_SELECTION_FLAT);
910 sel += opposite_corner;
911 } else {
912 sel = SPR_SELECT_TILE + SlopeToSpriteOffset(ti->tileh);
914 DrawSelectionSprite(sel, pal, ti, 7, FOUNDATION_PART_NORMAL);
917 static bool IsPartOfAutoLine(int px, int py)
919 px -= _thd.selstart.x;
920 py -= _thd.selstart.y;
922 if ((_thd.drawstyle & HT_DRAG_MASK) != HT_LINE) return false;
924 switch (_thd.drawstyle & HT_DIR_MASK) {
925 case HT_DIR_X: return py == 0; // x direction
926 case HT_DIR_Y: return px == 0; // y direction
927 case HT_DIR_HU: return px == -py || px == -py - 16; // horizontal upper
928 case HT_DIR_HL: return px == -py || px == -py + 16; // horizontal lower
929 case HT_DIR_VL: return px == py || px == py + 16; // vertical left
930 case HT_DIR_VR: return px == py || px == py - 16; // vertical right
931 default:
932 NOT_REACHED();
936 /* [direction][side] */
937 static const HighLightStyle _autorail_type[6][2] = {
938 { HT_DIR_X, HT_DIR_X },
939 { HT_DIR_Y, HT_DIR_Y },
940 { HT_DIR_HU, HT_DIR_HL },
941 { HT_DIR_HL, HT_DIR_HU },
942 { HT_DIR_VL, HT_DIR_VR },
943 { HT_DIR_VR, HT_DIR_VL }
946 #include "table/autorail.h"
949 * Draws autorail highlights.
951 * @param *ti TileInfo Tile that is being drawn
952 * @param autorail_type Offset into _AutorailTilehSprite[][]
954 static void DrawAutorailSelection(const TileInfo *ti, uint autorail_type)
956 SpriteID image;
957 PaletteID pal;
958 int offset;
960 FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
961 Slope autorail_tileh = RemoveHalftileSlope(ti->tileh);
962 if (IsHalftileSlope(ti->tileh)) {
963 static const uint _lower_rail[4] = { 5U, 2U, 4U, 3U };
964 Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
965 if (autorail_type != _lower_rail[halftile_corner]) {
966 foundation_part = FOUNDATION_PART_HALFTILE;
967 /* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
968 autorail_tileh = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
972 offset = _AutorailTilehSprite[autorail_tileh][autorail_type];
973 if (offset >= 0) {
974 image = SPR_AUTORAIL_BASE + offset;
975 pal = PAL_NONE;
976 } else {
977 image = SPR_AUTORAIL_BASE - offset;
978 pal = PALETTE_SEL_TILE_RED;
981 DrawSelectionSprite(image, _thd.make_square_red ? PALETTE_SEL_TILE_RED : pal, ti, 7, foundation_part);
984 enum TileHighlightType {
985 THT_NONE,
986 THT_WHITE,
987 THT_BLUE,
988 THT_RED,
991 const Station *_viewport_highlight_station; ///< Currently selected station for coverage area highlight
992 const Town *_viewport_highlight_town; ///< Currently selected town for coverage area highlight
995 * Get tile highlight type of coverage area for a given tile.
996 * @param t Tile that is being drawn
997 * @return Tile highlight type to draw
999 static TileHighlightType GetTileHighlightType(TileIndex t)
1001 if (_viewport_highlight_station != nullptr) {
1002 if (IsTileType(t, MP_STATION) && GetStationIndex(t) == _viewport_highlight_station->index) return THT_WHITE;
1003 if (_viewport_highlight_station->TileIsInCatchment(t)) return THT_BLUE;
1006 if (_viewport_highlight_town != nullptr) {
1007 if (IsTileType(t, MP_HOUSE)) {
1008 if (GetTownIndex(t) == _viewport_highlight_town->index) {
1009 TileHighlightType type = THT_RED;
1010 for (const Station *st : _viewport_highlight_town->stations_near) {
1011 if (st->owner != _current_company) continue;
1012 if (st->TileIsInCatchment(t)) return THT_BLUE;
1014 return type;
1016 } else if (IsTileType(t, MP_STATION)) {
1017 for (const Station *st : _viewport_highlight_town->stations_near) {
1018 if (st->owner != _current_company) continue;
1019 if (GetStationIndex(t) == st->index) return THT_WHITE;
1024 return THT_NONE;
1028 * Draw tile highlight for coverage area highlight.
1029 * @param *ti TileInfo Tile that is being drawn
1030 * @param tht Highlight type to draw.
1032 static void DrawTileHighlightType(const TileInfo *ti, TileHighlightType tht)
1034 switch (tht) {
1035 default:
1036 case THT_NONE: break;
1037 case THT_WHITE: DrawTileSelectionRect(ti, PAL_NONE); break;
1038 case THT_BLUE: DrawTileSelectionRect(ti, PALETTE_SEL_TILE_BLUE); break;
1039 case THT_RED: DrawTileSelectionRect(ti, PALETTE_SEL_TILE_RED); break;
1044 * Highlights tiles insede local authority of selected towns.
1045 * @param *ti TileInfo Tile that is being drawn
1047 static void HighlightTownLocalAuthorityTiles(const TileInfo *ti)
1049 /* Going through cases in order of computational time. */
1051 if (_town_local_authority_kdtree.Count() == 0) return;
1053 /* Tile belongs to town regardless of distance from town. */
1054 if (GetTileType(ti->tile) == MP_HOUSE) {
1055 if (!Town::GetByTile(ti->tile)->show_zone) return;
1057 DrawTileSelectionRect(ti, PALETTE_CRASH);
1058 return;
1061 /* If the closest town in the highlighted list is far, we can stop searching. */
1062 TownID tid = _town_local_authority_kdtree.FindNearest(TileX(ti->tile), TileY(ti->tile));
1063 Town *closest_highlighted_town = Town::Get(tid);
1065 if (DistanceManhattan(ti->tile, closest_highlighted_town->xy) >= _settings_game.economy.dist_local_authority) return;
1067 /* Tile is inside of the local autrhority distance of a highlighted town,
1068 but it is possible that a non-highlighted town is even closer. */
1069 Town *closest_town = ClosestTownFromTile(ti->tile, _settings_game.economy.dist_local_authority);
1071 if (closest_town->show_zone) {
1072 DrawTileSelectionRect(ti, PALETTE_CRASH);
1078 * Checks if the specified tile is selected and if so draws selection using correct selectionstyle.
1079 * @param *ti TileInfo Tile that is being drawn
1081 static void DrawTileSelection(const TileInfo *ti)
1083 /* Highlight tiles insede local authority of selected towns. */
1084 HighlightTownLocalAuthorityTiles(ti);
1086 /* Draw a red error square? */
1087 bool is_redsq = _thd.redsq == ti->tile;
1088 if (is_redsq) DrawTileSelectionRect(ti, PALETTE_TILE_RED_PULSATING);
1090 TileHighlightType tht = GetTileHighlightType(ti->tile);
1091 DrawTileHighlightType(ti, tht);
1093 /* No tile selection active? */
1094 if ((_thd.drawstyle & HT_DRAG_MASK) == HT_NONE) return;
1096 if (_thd.diagonal) { // We're drawing a 45 degrees rotated (diagonal) rectangle
1097 if (IsInsideRotatedRectangle((int)ti->x, (int)ti->y)) goto draw_inner;
1098 return;
1101 /* Inside the inner area? */
1102 if (IsInsideBS(ti->x, _thd.pos.x, _thd.size.x) &&
1103 IsInsideBS(ti->y, _thd.pos.y, _thd.size.y)) {
1104 draw_inner:
1105 if (_thd.drawstyle & HT_RECT) {
1106 if (!is_redsq) DrawTileSelectionRect(ti, _thd.make_square_red ? PALETTE_SEL_TILE_RED : PAL_NONE);
1107 } else if (_thd.drawstyle & HT_POINT) {
1108 /* Figure out the Z coordinate for the single dot. */
1109 int z = 0;
1110 FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
1111 if (ti->tileh & SLOPE_N) {
1112 z += TILE_HEIGHT;
1113 if (RemoveHalftileSlope(ti->tileh) == SLOPE_STEEP_N) z += TILE_HEIGHT;
1115 if (IsHalftileSlope(ti->tileh)) {
1116 Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
1117 if ((halftile_corner == CORNER_W) || (halftile_corner == CORNER_E)) z += TILE_HEIGHT;
1118 if (halftile_corner != CORNER_S) {
1119 foundation_part = FOUNDATION_PART_HALFTILE;
1120 if (IsSteepSlope(ti->tileh)) z -= TILE_HEIGHT;
1123 DrawSelectionSprite(_cur_dpi->zoom <= ZOOM_LVL_DETAIL ? SPR_DOT : SPR_DOT_SMALL, PAL_NONE, ti, z, foundation_part);
1124 } else if (_thd.drawstyle & HT_RAIL) {
1125 /* autorail highlight piece under cursor */
1126 HighLightStyle type = _thd.drawstyle & HT_DIR_MASK;
1127 assert(type < HT_DIR_END);
1128 DrawAutorailSelection(ti, _autorail_type[type][0]);
1129 } else if (IsPartOfAutoLine(ti->x, ti->y)) {
1130 /* autorail highlighting long line */
1131 HighLightStyle dir = _thd.drawstyle & HT_DIR_MASK;
1132 uint side;
1134 if (dir == HT_DIR_X || dir == HT_DIR_Y) {
1135 side = 0;
1136 } else {
1137 TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
1138 side = Delta(Delta(TileX(start), TileX(ti->tile)), Delta(TileY(start), TileY(ti->tile)));
1141 DrawAutorailSelection(ti, _autorail_type[dir][side]);
1143 return;
1146 /* Check if it's inside the outer area? */
1147 if (!is_redsq && (tht == THT_NONE || tht == THT_RED) && _thd.outersize.x > 0 &&
1148 IsInsideBS(ti->x, _thd.pos.x + _thd.offs.x, _thd.size.x + _thd.outersize.x) &&
1149 IsInsideBS(ti->y, _thd.pos.y + _thd.offs.y, _thd.size.y + _thd.outersize.y)) {
1150 /* Draw a blue rect. */
1151 DrawTileSelectionRect(ti, PALETTE_SEL_TILE_BLUE);
1152 return;
1157 * Returns the y coordinate in the viewport coordinate system where the given
1158 * tile is painted.
1159 * @param tile Any tile.
1160 * @return The viewport y coordinate where the tile is painted.
1162 static int GetViewportY(Point tile)
1164 /* Each increment in X or Y direction moves down by half a tile, i.e. TILE_PIXELS / 2. */
1165 return (tile.y * (int)(TILE_PIXELS / 2) + tile.x * (int)(TILE_PIXELS / 2) - TilePixelHeightOutsideMap(tile.x, tile.y)) << ZOOM_LVL_SHIFT;
1169 * Add the landscape to the viewport, i.e. all ground tiles and buildings.
1171 static void ViewportAddLandscape()
1173 assert(_vd.dpi.top <= _vd.dpi.top + _vd.dpi.height);
1174 assert(_vd.dpi.left <= _vd.dpi.left + _vd.dpi.width);
1176 Point upper_left = InverseRemapCoords(_vd.dpi.left, _vd.dpi.top);
1177 Point upper_right = InverseRemapCoords(_vd.dpi.left + _vd.dpi.width, _vd.dpi.top);
1179 /* Transformations between tile coordinates and viewport rows/columns: See vp_column_row
1180 * column = y - x
1181 * row = x + y
1182 * x = (row - column) / 2
1183 * y = (row + column) / 2
1184 * Note: (row, columns) pairs are only valid, if they are both even or both odd.
1187 /* Columns overlap with neighbouring columns by a half tile.
1188 * - Left column is column of upper_left (rounded down) and one column to the left.
1189 * - Right column is column of upper_right (rounded up) and one column to the right.
1190 * Note: Integer-division does not round down for negative numbers, so ensure rounding with another increment/decrement.
1192 int left_column = (upper_left.y - upper_left.x) / (int)TILE_SIZE - 2;
1193 int right_column = (upper_right.y - upper_right.x) / (int)TILE_SIZE + 2;
1195 int potential_bridge_height = ZOOM_LVL_BASE * TILE_HEIGHT * _settings_game.construction.max_bridge_height;
1197 /* Rows overlap with neighbouring rows by a half tile.
1198 * The first row that could possibly be visible is the row above upper_left (if it is at height 0).
1199 * Due to integer-division not rounding down for negative numbers, we need another decrement.
1201 int row = (upper_left.x + upper_left.y) / (int)TILE_SIZE - 2;
1202 bool last_row = false;
1203 for (; !last_row; row++) {
1204 last_row = true;
1205 for (int column = left_column; column <= right_column; column++) {
1206 /* Valid row/column? */
1207 if ((row + column) % 2 != 0) continue;
1209 Point tilecoord;
1210 tilecoord.x = (row - column) / 2;
1211 tilecoord.y = (row + column) / 2;
1212 assert(column == tilecoord.y - tilecoord.x);
1213 assert(row == tilecoord.y + tilecoord.x);
1215 TileType tile_type;
1216 TileInfo tile_info;
1217 _cur_ti = &tile_info;
1218 tile_info.x = tilecoord.x * TILE_SIZE; // FIXME tile_info should use signed integers
1219 tile_info.y = tilecoord.y * TILE_SIZE;
1221 if (IsInsideBS(tilecoord.x, 0, MapSizeX()) && IsInsideBS(tilecoord.y, 0, MapSizeY())) {
1222 /* This includes the south border at MapMaxX / MapMaxY. When terraforming we still draw tile selections there. */
1223 tile_info.tile = TileXY(tilecoord.x, tilecoord.y);
1224 tile_type = GetTileType(tile_info.tile);
1225 } else {
1226 tile_info.tile = INVALID_TILE;
1227 tile_type = MP_VOID;
1230 if (tile_type != MP_VOID) {
1231 /* We are inside the map => paint landscape. */
1232 tile_info.tileh = GetTilePixelSlope(tile_info.tile, &tile_info.z);
1233 } else {
1234 /* We are outside the map => paint black. */
1235 tile_info.tileh = GetTilePixelSlopeOutsideMap(tilecoord.x, tilecoord.y, &tile_info.z);
1238 int viewport_y = GetViewportY(tilecoord);
1240 if (viewport_y + MAX_TILE_EXTENT_BOTTOM < _vd.dpi.top) {
1241 /* The tile in this column is not visible yet.
1242 * Tiles in other columns may be visible, but we need more rows in any case. */
1243 last_row = false;
1244 continue;
1247 int min_visible_height = viewport_y - (_vd.dpi.top + _vd.dpi.height);
1248 bool tile_visible = min_visible_height <= 0;
1250 if (tile_type != MP_VOID) {
1251 /* Is tile with buildings visible? */
1252 if (min_visible_height < MAX_TILE_EXTENT_TOP) tile_visible = true;
1254 if (IsBridgeAbove(tile_info.tile)) {
1255 /* Is the bridge visible? */
1256 TileIndex bridge_tile = GetNorthernBridgeEnd(tile_info.tile);
1257 int bridge_height = ZOOM_LVL_BASE * (GetBridgePixelHeight(bridge_tile) - TilePixelHeight(tile_info.tile));
1258 if (min_visible_height < bridge_height + MAX_TILE_EXTENT_TOP) tile_visible = true;
1261 /* Would a higher bridge on a more southern tile be visible?
1262 * If yes, we need to loop over more rows to possibly find one. */
1263 if (min_visible_height < potential_bridge_height + MAX_TILE_EXTENT_TOP) last_row = false;
1264 } else {
1265 /* Outside of map. If we are on the north border of the map, there may still be a bridge visible,
1266 * so we need to loop over more rows to possibly find one. */
1267 if ((tilecoord.x <= 0 || tilecoord.y <= 0) && min_visible_height < potential_bridge_height + MAX_TILE_EXTENT_TOP) last_row = false;
1270 if (tile_visible) {
1271 last_row = false;
1272 _vd.foundation_part = FOUNDATION_PART_NONE;
1273 _vd.foundation[0] = -1;
1274 _vd.foundation[1] = -1;
1275 _vd.last_foundation_child[0] = nullptr;
1276 _vd.last_foundation_child[1] = nullptr;
1278 _tile_type_procs[tile_type]->draw_tile_proc(&tile_info);
1279 if (tile_info.tile != INVALID_TILE) DrawTileSelection(&tile_info);
1286 * Add a string to draw in the viewport
1287 * @param dpi current viewport area
1288 * @param small_from Zoomlevel from when the small font should be used
1289 * @param sign sign position and dimension
1290 * @param string_normal String for normal and 2x zoom level
1291 * @param string_small String for 4x and 8x zoom level
1292 * @param string_small_shadow Shadow string for 4x and 8x zoom level; or #STR_NULL if no shadow
1293 * @param colour colour of the sign background; or INVALID_COLOUR if transparent
1295 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)
1297 bool small = dpi->zoom >= small_from;
1299 int left = dpi->left;
1300 int top = dpi->top;
1301 int right = left + dpi->width;
1302 int bottom = top + dpi->height;
1304 int sign_height = ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM, dpi->zoom);
1305 int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, dpi->zoom);
1307 if (bottom < sign->top ||
1308 top > sign->top + sign_height ||
1309 right < sign->center - sign_half_width ||
1310 left > sign->center + sign_half_width) {
1311 return;
1314 if (!small) {
1315 AddStringToDraw(sign->center - sign_half_width, sign->top, string_normal, params_1, params_2, colour, sign->width_normal);
1316 } else {
1317 int shadow_offset = 0;
1318 if (string_small_shadow != STR_NULL) {
1319 shadow_offset = 4;
1320 AddStringToDraw(sign->center - sign_half_width + shadow_offset, sign->top, string_small_shadow, params_1, params_2, INVALID_COLOUR, sign->width_small);
1322 AddStringToDraw(sign->center - sign_half_width, sign->top - shadow_offset, string_small, params_1, params_2,
1323 colour, sign->width_small | 0x8000);
1327 static Rect ExpandRectWithViewportSignMargins(Rect r, ZoomLevel zoom)
1329 /* Pessimistically always use normal font, but also assume small font is never larger in either dimension */
1330 const int fh = FONT_HEIGHT_NORMAL;
1331 const int max_tw = _viewport_sign_maxwidth / 2 + 1;
1332 const int expand_y = ScaleByZoom(VPSM_TOP + fh + VPSM_BOTTOM, zoom);
1333 const int expand_x = ScaleByZoom(VPSM_LEFT + max_tw + VPSM_RIGHT, zoom);
1335 r.left -= expand_x;
1336 r.right += expand_x;
1337 r.top -= expand_y;
1338 r.bottom += expand_y;
1340 return r;
1343 static void ViewportAddKdtreeSigns(DrawPixelInfo *dpi)
1345 Rect search_rect{ dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height };
1346 search_rect = ExpandRectWithViewportSignMargins(search_rect, dpi->zoom);
1348 bool show_stations = HasBit(_display_opt, DO_SHOW_STATION_NAMES) && _game_mode != GM_MENU;
1349 bool show_waypoints = HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES) && _game_mode != GM_MENU;
1350 bool show_towns = HasBit(_display_opt, DO_SHOW_TOWN_NAMES) && _game_mode != GM_MENU;
1351 bool show_signs = HasBit(_display_opt, DO_SHOW_SIGNS) && !IsInvisibilitySet(TO_SIGNS);
1352 bool show_competitors = HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS);
1354 const BaseStation *st;
1355 const Sign *si;
1357 /* Collect all the items first and draw afterwards, to ensure layering */
1358 std::vector<const BaseStation *> stations;
1359 std::vector<const Town *> towns;
1360 std::vector<const Sign *> signs;
1362 _viewport_sign_kdtree.FindContained(search_rect.left, search_rect.top, search_rect.right, search_rect.bottom, [&](const ViewportSignKdtreeItem & item) {
1363 switch (item.type) {
1364 case ViewportSignKdtreeItem::VKI_STATION:
1365 if (!show_stations) break;
1366 st = BaseStation::Get(item.id.station);
1368 /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
1369 if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
1371 stations.push_back(st);
1372 break;
1374 case ViewportSignKdtreeItem::VKI_WAYPOINT:
1375 if (!show_waypoints) break;
1376 st = BaseStation::Get(item.id.station);
1378 /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
1379 if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
1381 stations.push_back(st);
1382 break;
1384 case ViewportSignKdtreeItem::VKI_TOWN:
1385 if (!show_towns) break;
1386 towns.push_back(Town::Get(item.id.town));
1387 break;
1389 case ViewportSignKdtreeItem::VKI_SIGN:
1390 if (!show_signs) break;
1391 si = Sign::Get(item.id.sign);
1393 /* Don't draw if sign is owned by another company and competitor signs should be hidden.
1394 * Note: It is intentional that also signs owned by OWNER_NONE are hidden. Bankrupt
1395 * companies can leave OWNER_NONE signs after them. */
1396 if (!show_competitors && _local_company != si->owner && si->owner != OWNER_DEITY) break;
1398 signs.push_back(si);
1399 break;
1401 default:
1402 NOT_REACHED();
1406 /* Layering order (bottom to top): Town names, signs, stations */
1408 for (const auto *t : towns) {
1409 ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &t->cache.sign,
1410 _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
1411 STR_VIEWPORT_TOWN_TINY_WHITE, STR_VIEWPORT_TOWN_TINY_BLACK,
1412 t->index, t->cache.population);
1415 for (const auto *si : signs) {
1416 ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &si->sign,
1417 STR_WHITE_SIGN,
1418 (IsTransparencySet(TO_SIGNS) || si->owner == OWNER_DEITY) ? STR_VIEWPORT_SIGN_SMALL_WHITE : STR_VIEWPORT_SIGN_SMALL_BLACK, STR_NULL,
1419 si->index, 0, (si->owner == OWNER_NONE) ? COLOUR_GREY : (si->owner == OWNER_DEITY ? INVALID_COLOUR : _company_colours[si->owner]));
1422 for (const auto *st : stations) {
1423 if (Station::IsExpected(st)) {
1424 /* Station */
1425 ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &st->sign,
1426 STR_VIEWPORT_STATION, STR_VIEWPORT_STATION_TINY, STR_NULL,
1427 st->index, st->facilities, (st->owner == OWNER_NONE || !st->IsInUse()) ? COLOUR_GREY : _company_colours[st->owner]);
1428 } else {
1429 /* Waypoint */
1430 ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &st->sign,
1431 STR_VIEWPORT_WAYPOINT, STR_VIEWPORT_WAYPOINT_TINY, STR_NULL,
1432 st->index, st->facilities, (st->owner == OWNER_NONE || !st->IsInUse()) ? COLOUR_GREY : _company_colours[st->owner]);
1439 * Update the position of the viewport sign.
1440 * @param center the (preferred) center of the viewport sign
1441 * @param top the new top of the sign
1442 * @param str the string to show in the sign
1443 * @param str_small the string to show when zoomed out. STR_NULL means same as \a str
1445 void ViewportSign::UpdatePosition(int center, int top, StringID str, StringID str_small)
1447 if (this->width_normal != 0) this->MarkDirty();
1449 this->top = top;
1451 char buffer[DRAW_STRING_BUFFER];
1453 GetString(buffer, str, lastof(buffer));
1454 this->width_normal = VPSM_LEFT + Align(GetStringBoundingBox(buffer).width, 2) + VPSM_RIGHT;
1455 this->center = center;
1457 /* zoomed out version */
1458 if (str_small != STR_NULL) {
1459 GetString(buffer, str_small, lastof(buffer));
1461 this->width_small = VPSM_LEFT + Align(GetStringBoundingBox(buffer, FS_SMALL).width, 2) + VPSM_RIGHT;
1463 this->MarkDirty();
1467 * Mark the sign dirty in all viewports.
1468 * @param maxzoom Maximum %ZoomLevel at which the text is visible.
1470 * @ingroup dirty
1472 void ViewportSign::MarkDirty(ZoomLevel maxzoom) const
1474 Rect zoomlevels[ZOOM_LVL_COUNT];
1476 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
1477 /* FIXME: This doesn't switch to width_small when appropriate. */
1478 zoomlevels[zoom].left = this->center - ScaleByZoom(this->width_normal / 2 + 1, zoom);
1479 zoomlevels[zoom].top = this->top - ScaleByZoom(1, zoom);
1480 zoomlevels[zoom].right = this->center + ScaleByZoom(this->width_normal / 2 + 1, zoom);
1481 zoomlevels[zoom].bottom = this->top + ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM + 1, zoom);
1484 for (const Window *w : Window::Iterate()) {
1485 Viewport *vp = w->viewport;
1486 if (vp != nullptr && vp->zoom <= maxzoom) {
1487 assert(vp->width != 0);
1488 Rect &zl = zoomlevels[vp->zoom];
1489 MarkViewportDirty(vp, zl.left, zl.top, zl.right, zl.bottom);
1494 static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
1496 for (const TileSpriteToDraw &ts : *tstdv) {
1497 DrawSpriteViewport(ts.image, ts.pal, ts.x, ts.y, ts.sub);
1501 /** This fallback sprite checker always exists. */
1502 static bool ViewportSortParentSpritesChecker()
1504 return true;
1507 /** Sort parent sprites pointer array replicating the way original sorter did it. */
1508 static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
1510 if (psdv->size() < 2) return;
1512 /* We rely on sprites being, for the most part, already ordered.
1513 * So we don't need to move many of them and can keep track of their
1514 * order efficiently by using stack. We always move sprites to the front
1515 * of the current position, i.e. to the top of the stack.
1516 * Also use special constants to indicate sorting state without
1517 * adding extra fields to ParentSpriteToDraw structure.
1519 const uint32 ORDER_COMPARED = UINT32_MAX; // Sprite was compared but we still need to compare the ones preceding it
1520 const uint32 ORDER_RETURNED = UINT32_MAX - 1; // Makr sorted sprite in case there are other occurrences of it in the stack
1521 std::stack<ParentSpriteToDraw *> sprite_order;
1522 uint32 next_order = 0;
1524 std::forward_list<std::pair<int64, ParentSpriteToDraw *>> sprite_list; // We store sprites in a list sorted by xmin+ymin
1526 /* Initialize sprite list and order. */
1527 for (auto p = psdv->rbegin(); p != psdv->rend(); p++) {
1528 sprite_list.push_front(std::make_pair((*p)->xmin + (*p)->ymin, *p));
1529 sprite_order.push(*p);
1530 (*p)->order = next_order++;
1533 sprite_list.sort();
1535 std::vector<ParentSpriteToDraw *> preceding; // Temporarily stores sprites that precede current and their position in the list
1536 auto preceding_prev = sprite_list.begin(); // Store iterator in case we need to delete a single preciding sprite
1537 auto out = psdv->begin(); // Iterator to output sorted sprites
1539 while (!sprite_order.empty()) {
1541 auto s = sprite_order.top();
1542 sprite_order.pop();
1544 /* Sprite is already sorted, ignore it. */
1545 if (s->order == ORDER_RETURNED) continue;
1547 /* Sprite was already compared, just need to output it. */
1548 if (s->order == ORDER_COMPARED) {
1549 *(out++) = s;
1550 s->order = ORDER_RETURNED;
1551 continue;
1554 preceding.clear();
1556 /* We only need sprites with xmin <= s->xmax && ymin <= s->ymax && zmin <= s->zmax
1557 * So by iterating sprites with xmin + ymin <= s->xmax + s->ymax
1558 * we get all we need and some more that we filter out later.
1559 * We don't include zmin into the sum as there are usually more neighbors on x and y than z
1560 * so including it will actually increase the amount of false positives.
1561 * Also min coordinates can be > max so using max(xmin, xmax) + max(ymin, ymax)
1562 * to ensure that we iterate the current sprite as we need to remove it from the list.
1564 auto ssum = std::max(s->xmax, s->xmin) + std::max(s->ymax, s->ymin);
1565 auto prev = sprite_list.before_begin();
1566 auto x = sprite_list.begin();
1567 while (x != sprite_list.end() && ((*x).first <= ssum)) {
1568 auto p = (*x).second;
1569 if (p == s) {
1570 /* We found the current sprite, remove it and move on. */
1571 x = sprite_list.erase_after(prev);
1572 continue;
1575 auto p_prev = prev;
1576 prev = x++;
1578 if (s->xmax < p->xmin || s->ymax < p->ymin || s->zmax < p->zmin) continue;
1579 if (s->xmin <= p->xmax && // overlap in X?
1580 s->ymin <= p->ymax && // overlap in Y?
1581 s->zmin <= p->zmax) { // overlap in Z?
1582 if (s->xmin + s->xmax + s->ymin + s->ymax + s->zmin + s->zmax <=
1583 p->xmin + p->xmax + p->ymin + p->ymax + p->zmin + p->zmax) {
1584 continue;
1587 preceding.push_back(p);
1588 preceding_prev = p_prev;
1591 if (preceding.empty()) {
1592 /* No preceding sprites, add current one to the output */
1593 *(out++) = s;
1594 s->order = ORDER_RETURNED;
1595 continue;
1598 /* Optimization for the case when we only have 1 sprite to move. */
1599 if (preceding.size() == 1) {
1600 auto p = preceding[0];
1601 /* We can only output the preceding sprite if there can't be any other sprites preceding it. */
1602 if (p->xmax <= s->xmax && p->ymax <= s->ymax && p->zmax <= s->zmax) {
1603 p->order = ORDER_RETURNED;
1604 s->order = ORDER_RETURNED;
1605 sprite_list.erase_after(preceding_prev);
1606 *(out++) = p;
1607 *(out++) = s;
1608 continue;
1612 /* Sort all preceding sprites by order and assign new orders in reverse (as original sorter did). */
1613 std::sort(preceding.begin(), preceding.end(), [](const ParentSpriteToDraw *a, const ParentSpriteToDraw *b) {
1614 return a->order > b->order;
1617 s->order = ORDER_COMPARED;
1618 sprite_order.push(s); // Still need to output so push it back for now
1620 for (auto p: preceding) {
1621 p->order = next_order++;
1622 sprite_order.push(p);
1628 static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
1630 for (const ParentSpriteToDraw *ps : *psd) {
1631 if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSpriteViewport(ps->image, ps->pal, ps->x, ps->y, ps->sub);
1633 int child_idx = ps->first_child;
1634 while (child_idx >= 0) {
1635 const ChildScreenSpriteToDraw *cs = csstdv->data() + child_idx;
1636 child_idx = cs->next;
1637 DrawSpriteViewport(cs->image, cs->pal, ps->left + cs->x, ps->top + cs->y, cs->sub);
1643 * Draws the bounding boxes of all ParentSprites
1644 * @param psd Array of ParentSprites
1646 static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
1648 for (const ParentSpriteToDraw *ps : *psd) {
1649 Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner
1650 Point pt2 = RemapCoords(ps->xmin , ps->ymax + 1, ps->zmax + 1); // top left corner
1651 Point pt3 = RemapCoords(ps->xmax + 1, ps->ymin , ps->zmax + 1); // top right corner
1652 Point pt4 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmin ); // bottom front corner
1654 DrawBox( pt1.x, pt1.y,
1655 pt2.x - pt1.x, pt2.y - pt1.y,
1656 pt3.x - pt1.x, pt3.y - pt1.y,
1657 pt4.x - pt1.x, pt4.y - pt1.y);
1662 * Draw/colour the blocks that have been redrawn.
1664 static void ViewportDrawDirtyBlocks()
1666 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
1667 const DrawPixelInfo *dpi = _cur_dpi;
1668 void *dst;
1669 int right = UnScaleByZoom(dpi->width, dpi->zoom);
1670 int bottom = UnScaleByZoom(dpi->height, dpi->zoom);
1672 int colour = _string_colourmap[_dirty_block_colour & 0xF];
1674 dst = dpi->dst_ptr;
1676 byte bo = UnScaleByZoom(dpi->left + dpi->top, dpi->zoom) & 1;
1677 do {
1678 for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8)colour);
1679 dst = blitter->MoveTo(dst, 0, 1);
1680 } while (--bottom > 0);
1683 static void ViewportDrawStrings(ZoomLevel zoom, const StringSpriteToDrawVector *sstdv)
1685 for (const StringSpriteToDraw &ss : *sstdv) {
1686 TextColour colour = TC_BLACK;
1687 bool small = HasBit(ss.width, 15);
1688 int w = GB(ss.width, 0, 15);
1689 int x = UnScaleByZoom(ss.x, zoom);
1690 int y = UnScaleByZoom(ss.y, zoom);
1691 int h = VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM;
1693 SetDParam(0, ss.params[0]);
1694 SetDParam(1, ss.params[1]);
1696 if (ss.colour != INVALID_COLOUR) {
1697 /* Do not draw signs nor station names if they are set invisible */
1698 if (IsInvisibilitySet(TO_SIGNS) && ss.string != STR_WHITE_SIGN) continue;
1700 if (IsTransparencySet(TO_SIGNS) && ss.string != STR_WHITE_SIGN) {
1701 /* Don't draw the rectangle.
1702 * Real colours need the TC_IS_PALETTE_COLOUR flag.
1703 * Otherwise colours from _string_colourmap are assumed. */
1704 colour = (TextColour)_colour_gradient[ss.colour][6] | TC_IS_PALETTE_COLOUR;
1705 } else {
1706 /* Draw the rectangle if 'transparent station signs' is off,
1707 * or if we are drawing a general text sign (STR_WHITE_SIGN). */
1708 DrawFrameRect(
1709 x, y, x + w, y + h, ss.colour,
1710 IsTransparencySet(TO_SIGNS) ? FR_TRANSPARENT : FR_NONE
1715 DrawString(x + VPSM_LEFT, x + w - 1 - VPSM_RIGHT, y + VPSM_TOP, ss.string, colour, SA_HOR_CENTER);
1719 void ViewportDoDraw(const Viewport *vp, int left, int top, int right, int bottom)
1721 DrawPixelInfo *old_dpi = _cur_dpi;
1722 _cur_dpi = &_vd.dpi;
1724 _vd.dpi.zoom = vp->zoom;
1725 int mask = ScaleByZoom(-1, vp->zoom);
1727 _vd.combine_sprites = SPRITE_COMBINE_NONE;
1729 _vd.dpi.width = (right - left) & mask;
1730 _vd.dpi.height = (bottom - top) & mask;
1731 _vd.dpi.left = left & mask;
1732 _vd.dpi.top = top & mask;
1733 _vd.dpi.pitch = old_dpi->pitch;
1734 _vd.last_child = nullptr;
1736 int x = UnScaleByZoom(_vd.dpi.left - (vp->virtual_left & mask), vp->zoom) + vp->left;
1737 int y = UnScaleByZoom(_vd.dpi.top - (vp->virtual_top & mask), vp->zoom) + vp->top;
1739 _vd.dpi.dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(old_dpi->dst_ptr, x - old_dpi->left, y - old_dpi->top);
1741 ViewportAddLandscape();
1742 ViewportAddVehicles(&_vd.dpi);
1744 ViewportAddKdtreeSigns(&_vd.dpi);
1746 DrawTextEffects(&_vd.dpi);
1748 if (_vd.tile_sprites_to_draw.size() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
1750 for (auto &psd : _vd.parent_sprites_to_draw) {
1751 _vd.parent_sprites_to_sort.push_back(&psd);
1754 _vp_sprite_sorter(&_vd.parent_sprites_to_sort);
1755 ViewportDrawParentSprites(&_vd.parent_sprites_to_sort, &_vd.child_screen_sprites_to_draw);
1757 if (_draw_bounding_boxes) ViewportDrawBoundingBoxes(&_vd.parent_sprites_to_sort);
1758 if (_draw_dirty_blocks) ViewportDrawDirtyBlocks();
1760 DrawPixelInfo dp = _vd.dpi;
1761 ZoomLevel zoom = _vd.dpi.zoom;
1762 dp.zoom = ZOOM_LVL_NORMAL;
1763 dp.width = UnScaleByZoom(dp.width, zoom);
1764 dp.height = UnScaleByZoom(dp.height, zoom);
1765 _cur_dpi = &dp;
1767 if (vp->overlay != nullptr && vp->overlay->GetCargoMask() != 0 && vp->overlay->GetCompanyMask() != 0) {
1768 /* translate to window coordinates */
1769 dp.left = x;
1770 dp.top = y;
1771 vp->overlay->Draw(&dp);
1774 if (_vd.string_sprites_to_draw.size() != 0) {
1775 /* translate to world coordinates */
1776 dp.left = UnScaleByZoom(_vd.dpi.left, zoom);
1777 dp.top = UnScaleByZoom(_vd.dpi.top, zoom);
1778 ViewportDrawStrings(zoom, &_vd.string_sprites_to_draw);
1781 _cur_dpi = old_dpi;
1783 _vd.string_sprites_to_draw.clear();
1784 _vd.tile_sprites_to_draw.clear();
1785 _vd.parent_sprites_to_draw.clear();
1786 _vd.parent_sprites_to_sort.clear();
1787 _vd.child_screen_sprites_to_draw.clear();
1790 static inline void ViewportDraw(const Viewport *vp, int left, int top, int right, int bottom)
1792 if (right <= vp->left || bottom <= vp->top) return;
1794 if (left >= vp->left + vp->width) return;
1796 if (left < vp->left) left = vp->left;
1797 if (right > vp->left + vp->width) right = vp->left + vp->width;
1799 if (top >= vp->top + vp->height) return;
1801 if (top < vp->top) top = vp->top;
1802 if (bottom > vp->top + vp->height) bottom = vp->top + vp->height;
1804 ViewportDoDraw(vp,
1805 ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
1806 ScaleByZoom(top - vp->top, vp->zoom) + vp->virtual_top,
1807 ScaleByZoom(right - vp->left, vp->zoom) + vp->virtual_left,
1808 ScaleByZoom(bottom - vp->top, vp->zoom) + vp->virtual_top
1813 * Draw the viewport of this window.
1815 void Window::DrawViewport() const
1817 PerformanceAccumulator framerate(PFE_DRAWWORLD);
1819 DrawPixelInfo *dpi = _cur_dpi;
1821 dpi->left += this->left;
1822 dpi->top += this->top;
1824 ViewportDraw(this->viewport, dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height);
1826 dpi->left -= this->left;
1827 dpi->top -= this->top;
1831 * Ensure that a given viewport has a valid scroll position.
1833 * There must be a visible piece of the map in the center of the viewport.
1834 * If there isn't, the viewport will be scrolled to nearest such location.
1836 * @param vp The viewport.
1837 * @param[in,out] scroll_x Viewport X scroll.
1838 * @param[in,out] scroll_y Viewport Y scroll.
1840 static inline void ClampViewportToMap(const Viewport *vp, int *scroll_x, int *scroll_y)
1842 /* Centre of the viewport is hot spot. */
1843 Point pt = {
1844 *scroll_x + vp->virtual_width / 2,
1845 *scroll_y + vp->virtual_height / 2
1848 /* Find nearest tile that is within borders of the map. */
1849 bool clamped;
1850 pt = InverseRemapCoords2(pt.x, pt.y, true, &clamped);
1852 if (clamped) {
1853 /* Convert back to viewport coordinates and remove centering. */
1854 pt = RemapCoords2(pt.x, pt.y);
1855 *scroll_x = pt.x - vp->virtual_width / 2;
1856 *scroll_y = pt.y - vp->virtual_height / 2;
1861 * Update the viewport position being displayed.
1862 * @param w %Window owning the viewport.
1864 void UpdateViewportPosition(Window *w)
1866 const Viewport *vp = w->viewport;
1868 if (w->viewport->follow_vehicle != INVALID_VEHICLE) {
1869 const Vehicle *veh = Vehicle::Get(w->viewport->follow_vehicle);
1870 Point pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
1872 w->viewport->scrollpos_x = pt.x;
1873 w->viewport->scrollpos_y = pt.y;
1874 SetViewportPosition(w, pt.x, pt.y);
1875 } else {
1876 /* Ensure the destination location is within the map */
1877 ClampViewportToMap(vp, &w->viewport->dest_scrollpos_x, &w->viewport->dest_scrollpos_y);
1879 int delta_x = w->viewport->dest_scrollpos_x - w->viewport->scrollpos_x;
1880 int delta_y = w->viewport->dest_scrollpos_y - w->viewport->scrollpos_y;
1882 bool update_overlay = false;
1883 if (delta_x != 0 || delta_y != 0) {
1884 if (_settings_client.gui.smooth_scroll) {
1885 int max_scroll = ScaleByMapSize1D(512 * ZOOM_LVL_BASE);
1886 /* Not at our desired position yet... */
1887 w->viewport->scrollpos_x += Clamp(DivAwayFromZero(delta_x, 4), -max_scroll, max_scroll);
1888 w->viewport->scrollpos_y += Clamp(DivAwayFromZero(delta_y, 4), -max_scroll, max_scroll);
1889 } else {
1890 w->viewport->scrollpos_x = w->viewport->dest_scrollpos_x;
1891 w->viewport->scrollpos_y = w->viewport->dest_scrollpos_y;
1893 update_overlay = (w->viewport->scrollpos_x == w->viewport->dest_scrollpos_x &&
1894 w->viewport->scrollpos_y == w->viewport->dest_scrollpos_y);
1897 ClampViewportToMap(vp, &w->viewport->scrollpos_x, &w->viewport->scrollpos_y);
1899 SetViewportPosition(w, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
1900 if (update_overlay) RebuildViewportOverlay(w);
1905 * Marks a viewport as dirty for repaint if it displays (a part of) the area the needs to be repainted.
1906 * @param vp The viewport to mark as dirty
1907 * @param left Left edge of area to repaint
1908 * @param top Top edge of area to repaint
1909 * @param right Right edge of area to repaint
1910 * @param bottom Bottom edge of area to repaint
1911 * @return true if the viewport contains a dirty block
1912 * @ingroup dirty
1914 static bool MarkViewportDirty(const Viewport *vp, int left, int top, int right, int bottom)
1916 /* Rounding wrt. zoom-out level */
1917 right += (1 << vp->zoom) - 1;
1918 bottom += (1 << vp->zoom) - 1;
1920 right -= vp->virtual_left;
1921 if (right <= 0) return false;
1923 bottom -= vp->virtual_top;
1924 if (bottom <= 0) return false;
1926 left = std::max(0, left - vp->virtual_left);
1928 if (left >= vp->virtual_width) return false;
1930 top = std::max(0, top - vp->virtual_top);
1932 if (top >= vp->virtual_height) return false;
1934 AddDirtyBlock(
1935 UnScaleByZoomLower(left, vp->zoom) + vp->left,
1936 UnScaleByZoomLower(top, vp->zoom) + vp->top,
1937 UnScaleByZoom(right, vp->zoom) + vp->left + 1,
1938 UnScaleByZoom(bottom, vp->zoom) + vp->top + 1
1941 return true;
1945 * Mark all viewports that display an area as dirty (in need of repaint).
1946 * @param left Left edge of area to repaint. (viewport coordinates, that is wrt. #ZOOM_LVL_NORMAL)
1947 * @param top Top edge of area to repaint. (viewport coordinates, that is wrt. #ZOOM_LVL_NORMAL)
1948 * @param right Right edge of area to repaint. (viewport coordinates, that is wrt. #ZOOM_LVL_NORMAL)
1949 * @param bottom Bottom edge of area to repaint. (viewport coordinates, that is wrt. #ZOOM_LVL_NORMAL)
1950 * @return true if at least one viewport has a dirty block
1951 * @ingroup dirty
1953 bool MarkAllViewportsDirty(int left, int top, int right, int bottom)
1955 bool dirty = false;
1957 for (const Window *w : Window::Iterate()) {
1958 Viewport *vp = w->viewport;
1959 if (vp != nullptr) {
1960 assert(vp->width != 0);
1961 if (MarkViewportDirty(vp, left, top, right, bottom)) dirty = true;
1965 return dirty;
1968 void ConstrainAllViewportsZoom()
1970 for (Window *w : Window::Iterate()) {
1971 if (w->viewport == nullptr) continue;
1973 ZoomLevel zoom = static_cast<ZoomLevel>(Clamp(w->viewport->zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max));
1974 if (zoom != w->viewport->zoom) {
1975 while (w->viewport->zoom < zoom) DoZoomInOutWindow(ZOOM_OUT, w);
1976 while (w->viewport->zoom > zoom) DoZoomInOutWindow(ZOOM_IN, w);
1982 * Mark a tile given by its index dirty for repaint.
1983 * @param tile The tile to mark dirty.
1984 * @param bridge_level_offset Height of bridge on tile to also mark dirty. (Height level relative to north corner.)
1985 * @param tile_height_override Height of the tile (#TileHeight).
1986 * @ingroup dirty
1988 void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
1990 Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, tile_height_override * TILE_HEIGHT);
1991 MarkAllViewportsDirty(
1992 pt.x - MAX_TILE_EXTENT_LEFT,
1993 pt.y - MAX_TILE_EXTENT_TOP - ZOOM_LVL_BASE * TILE_HEIGHT * bridge_level_offset,
1994 pt.x + MAX_TILE_EXTENT_RIGHT,
1995 pt.y + MAX_TILE_EXTENT_BOTTOM);
1999 * Marks the selected tiles as dirty.
2001 * This function marks the selected tiles as dirty for repaint
2003 * @ingroup dirty
2005 static void SetSelectionTilesDirty()
2007 int x_size = _thd.size.x;
2008 int y_size = _thd.size.y;
2010 if (!_thd.diagonal) { // Selecting in a straight rectangle (or a single square)
2011 int x_start = _thd.pos.x;
2012 int y_start = _thd.pos.y;
2014 if (_thd.outersize.x != 0) {
2015 x_size += _thd.outersize.x;
2016 x_start += _thd.offs.x;
2017 y_size += _thd.outersize.y;
2018 y_start += _thd.offs.y;
2021 x_size -= TILE_SIZE;
2022 y_size -= TILE_SIZE;
2024 assert(x_size >= 0);
2025 assert(y_size >= 0);
2027 int x_end = Clamp(x_start + x_size, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
2028 int y_end = Clamp(y_start + y_size, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
2030 x_start = Clamp(x_start, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
2031 y_start = Clamp(y_start, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
2033 /* make sure everything is multiple of TILE_SIZE */
2034 assert((x_end | y_end | x_start | y_start) % TILE_SIZE == 0);
2036 /* How it works:
2037 * Suppose we have to mark dirty rectangle of 3x4 tiles:
2039 * xxx
2040 * xxxxx
2041 * xxxxx
2042 * xxx
2044 * This algorithm marks dirty columns of tiles, so it is done in 3+4-1 steps:
2045 * 1) x 2) x
2046 * xxx Oxx
2047 * Oxxxx xOxxx
2048 * xxxxx Oxxxx
2049 * xxx xxx
2050 * x x
2051 * And so forth...
2054 int top_x = x_end; // coordinates of top dirty tile
2055 int top_y = y_start;
2056 int bot_x = top_x; // coordinates of bottom dirty tile
2057 int bot_y = top_y;
2059 do {
2060 /* topmost dirty point */
2061 TileIndex top_tile = TileVirtXY(top_x, top_y);
2062 Point top = RemapCoords(top_x, top_y, GetTileMaxPixelZ(top_tile));
2064 /* bottommost point */
2065 TileIndex bottom_tile = TileVirtXY(bot_x, bot_y);
2066 Point bot = RemapCoords(bot_x + TILE_SIZE, bot_y + TILE_SIZE, GetTilePixelZ(bottom_tile)); // bottommost point
2068 /* the 'x' coordinate of 'top' and 'bot' is the same (and always in the same distance from tile middle),
2069 * tile height/slope affects only the 'y' on-screen coordinate! */
2071 int l = top.x - TILE_PIXELS * ZOOM_LVL_BASE; // 'x' coordinate of left side of the dirty rectangle
2072 int t = top.y; // 'y' coordinate of top side of the dirty rectangle
2073 int r = top.x + TILE_PIXELS * ZOOM_LVL_BASE; // 'x' coordinate of right side of the dirty rectangle
2074 int b = bot.y; // 'y' coordinate of bottom side of the dirty rectangle
2076 static const int OVERLAY_WIDTH = 4 * ZOOM_LVL_BASE; // part of selection sprites is drawn outside the selected area (in particular: terraforming)
2078 /* For halftile foundations on SLOPE_STEEP_S the sprite extents some more towards the top */
2079 MarkAllViewportsDirty(l - OVERLAY_WIDTH, t - OVERLAY_WIDTH - TILE_HEIGHT * ZOOM_LVL_BASE, r + OVERLAY_WIDTH, b + OVERLAY_WIDTH);
2081 /* haven't we reached the topmost tile yet? */
2082 if (top_x != x_start) {
2083 top_x -= TILE_SIZE;
2084 } else {
2085 top_y += TILE_SIZE;
2088 /* the way the bottom tile changes is different when we reach the bottommost tile */
2089 if (bot_y != y_end) {
2090 bot_y += TILE_SIZE;
2091 } else {
2092 bot_x -= TILE_SIZE;
2094 } while (bot_x >= top_x);
2095 } else { // Selecting in a 45 degrees rotated (diagonal) rectangle.
2096 /* a_size, b_size describe a rectangle with rotated coordinates */
2097 int a_size = x_size + y_size, b_size = x_size - y_size;
2099 int interval_a = a_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
2100 int interval_b = b_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
2102 for (int a = -interval_a; a != a_size + interval_a; a += interval_a) {
2103 for (int b = -interval_b; b != b_size + interval_b; b += interval_b) {
2104 uint x = (_thd.pos.x + (a + b) / 2) / TILE_SIZE;
2105 uint y = (_thd.pos.y + (a - b) / 2) / TILE_SIZE;
2107 if (x < MapMaxX() && y < MapMaxY()) {
2108 MarkTileDirtyByTile(TileXY(x, y));
2116 void SetSelectionRed(bool b)
2118 _thd.make_square_red = b;
2119 SetSelectionTilesDirty();
2123 * Test whether a sign is below the mouse
2124 * @param vp the clicked viewport
2125 * @param x X position of click
2126 * @param y Y position of click
2127 * @param sign the sign to check
2128 * @return true if the sign was hit
2130 static bool CheckClickOnViewportSign(const Viewport *vp, int x, int y, const ViewportSign *sign)
2132 bool small = (vp->zoom >= ZOOM_LVL_OUT_16X);
2133 int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, vp->zoom);
2134 int sign_height = ScaleByZoom(VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM, vp->zoom);
2136 return y >= sign->top && y < sign->top + sign_height &&
2137 x >= sign->center - sign_half_width && x < sign->center + sign_half_width;
2142 * Check whether any viewport sign was clicked, and dispatch the click.
2143 * @param vp the clicked viewport
2144 * @param x X position of click
2145 * @param y Y position of click
2146 * @return true if the sign was hit
2148 static bool CheckClickOnViewportSign(const Viewport *vp, int x, int y)
2150 if (_game_mode == GM_MENU) return false;
2152 x = ScaleByZoom(x - vp->left, vp->zoom) + vp->virtual_left;
2153 y = ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top;
2155 Rect search_rect{ x - 1, y - 1, x + 1, y + 1 };
2156 search_rect = ExpandRectWithViewportSignMargins(search_rect, vp->zoom);
2158 bool show_stations = HasBit(_display_opt, DO_SHOW_STATION_NAMES) && !IsInvisibilitySet(TO_SIGNS);
2159 bool show_waypoints = HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES) && !IsInvisibilitySet(TO_SIGNS);
2160 bool show_towns = HasBit(_display_opt, DO_SHOW_TOWN_NAMES);
2161 bool show_signs = HasBit(_display_opt, DO_SHOW_SIGNS) && !IsInvisibilitySet(TO_SIGNS);
2162 bool show_competitors = HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS);
2164 /* Topmost of each type that was hit */
2165 BaseStation *st = nullptr, *last_st = nullptr;
2166 Town *t = nullptr, *last_t = nullptr;
2167 Sign *si = nullptr, *last_si = nullptr;
2169 /* See ViewportAddKdtreeSigns() for details on the search logic */
2170 _viewport_sign_kdtree.FindContained(search_rect.left, search_rect.top, search_rect.right, search_rect.bottom, [&](const ViewportSignKdtreeItem & item) {
2171 switch (item.type) {
2172 case ViewportSignKdtreeItem::VKI_STATION:
2173 if (!show_stations) break;
2174 st = BaseStation::Get(item.id.station);
2175 if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
2176 if (CheckClickOnViewportSign(vp, x, y, &st->sign)) last_st = st;
2177 break;
2179 case ViewportSignKdtreeItem::VKI_WAYPOINT:
2180 if (!show_waypoints) break;
2181 st = BaseStation::Get(item.id.station);
2182 if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
2183 if (CheckClickOnViewportSign(vp, x, y, &st->sign)) last_st = st;
2184 break;
2186 case ViewportSignKdtreeItem::VKI_TOWN:
2187 if (!show_towns) break;
2188 t = Town::Get(item.id.town);
2189 if (CheckClickOnViewportSign(vp, x, y, &t->cache.sign)) last_t = t;
2190 break;
2192 case ViewportSignKdtreeItem::VKI_SIGN:
2193 if (!show_signs) break;
2194 si = Sign::Get(item.id.sign);
2195 if (!show_competitors && _local_company != si->owner && si->owner != OWNER_DEITY) break;
2196 if (CheckClickOnViewportSign(vp, x, y, &si->sign)) last_si = si;
2197 break;
2199 default:
2200 NOT_REACHED();
2204 /* Select which hit to handle based on priority */
2205 if (last_st != nullptr) {
2206 if (Station::IsExpected(last_st)) {
2207 ShowStationViewWindow(last_st->index);
2208 } else {
2209 ShowWaypointWindow(Waypoint::From(last_st));
2211 return true;
2212 } else if (last_t != nullptr) {
2213 ShowTownViewWindow(last_t->index);
2214 return true;
2215 } else if (last_si != nullptr) {
2216 HandleClickOnSign(last_si);
2217 return true;
2218 } else {
2219 return false;
2224 ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeStation(StationID id)
2226 ViewportSignKdtreeItem item;
2227 item.type = VKI_STATION;
2228 item.id.station = id;
2230 const Station *st = Station::Get(id);
2231 assert(st->sign.kdtree_valid);
2232 item.center = st->sign.center;
2233 item.top = st->sign.top;
2235 /* Assume the sign can be a candidate for drawing, so measure its width */
2236 _viewport_sign_maxwidth = std::max<int>(_viewport_sign_maxwidth, st->sign.width_normal);
2238 return item;
2241 ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeWaypoint(StationID id)
2243 ViewportSignKdtreeItem item;
2244 item.type = VKI_WAYPOINT;
2245 item.id.station = id;
2247 const Waypoint *st = Waypoint::Get(id);
2248 assert(st->sign.kdtree_valid);
2249 item.center = st->sign.center;
2250 item.top = st->sign.top;
2252 /* Assume the sign can be a candidate for drawing, so measure its width */
2253 _viewport_sign_maxwidth = std::max<int>(_viewport_sign_maxwidth, st->sign.width_normal);
2255 return item;
2258 ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeTown(TownID id)
2260 ViewportSignKdtreeItem item;
2261 item.type = VKI_TOWN;
2262 item.id.town = id;
2264 const Town *town = Town::Get(id);
2265 assert(town->cache.sign.kdtree_valid);
2266 item.center = town->cache.sign.center;
2267 item.top = town->cache.sign.top;
2269 /* Assume the sign can be a candidate for drawing, so measure its width */
2270 _viewport_sign_maxwidth = std::max<int>(_viewport_sign_maxwidth, town->cache.sign.width_normal);
2272 return item;
2275 ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeSign(SignID id)
2277 ViewportSignKdtreeItem item;
2278 item.type = VKI_SIGN;
2279 item.id.sign = id;
2281 const Sign *sign = Sign::Get(id);
2282 assert(sign->sign.kdtree_valid);
2283 item.center = sign->sign.center;
2284 item.top = sign->sign.top;
2286 /* Assume the sign can be a candidate for drawing, so measure its width */
2287 _viewport_sign_maxwidth = std::max<int>(_viewport_sign_maxwidth, sign->sign.width_normal);
2289 return item;
2292 void RebuildViewportKdtree()
2294 /* Reset biggest size sign seen */
2295 _viewport_sign_maxwidth = 0;
2297 std::vector<ViewportSignKdtreeItem> items;
2298 items.reserve(BaseStation::GetNumItems() + Town::GetNumItems() + Sign::GetNumItems());
2300 for (const Station *st : Station::Iterate()) {
2301 if (st->sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeStation(st->index));
2304 for (const Waypoint *wp : Waypoint::Iterate()) {
2305 if (wp->sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeWaypoint(wp->index));
2308 for (const Town *town : Town::Iterate()) {
2309 if (town->cache.sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeTown(town->index));
2312 for (const Sign *sign : Sign::Iterate()) {
2313 if (sign->sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeSign(sign->index));
2316 _viewport_sign_kdtree.Build(items.begin(), items.end());
2320 static bool CheckClickOnLandscape(const Viewport *vp, int x, int y)
2322 Point pt = TranslateXYToTileCoord(vp, x, y);
2324 if (pt.x != -1) return ClickTile(TileVirtXY(pt.x, pt.y));
2325 return true;
2328 static void PlaceObject()
2330 Point pt;
2331 Window *w;
2333 pt = GetTileBelowCursor();
2334 if (pt.x == -1) return;
2336 if ((_thd.place_mode & HT_DRAG_MASK) == HT_POINT) {
2337 pt.x += TILE_SIZE / 2;
2338 pt.y += TILE_SIZE / 2;
2341 _tile_fract_coords.x = pt.x & TILE_UNIT_MASK;
2342 _tile_fract_coords.y = pt.y & TILE_UNIT_MASK;
2344 w = _thd.GetCallbackWnd();
2345 if (w != nullptr) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
2349 bool HandleViewportClicked(const Viewport *vp, int x, int y)
2351 const Vehicle *v = CheckClickOnVehicle(vp, x, y);
2353 if (_thd.place_mode & HT_VEHICLE) {
2354 if (v != nullptr && VehicleClicked(v)) return true;
2357 /* Vehicle placement mode already handled above. */
2358 if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
2359 PlaceObject();
2360 return true;
2363 if (CheckClickOnViewportSign(vp, x, y)) return true;
2364 bool result = CheckClickOnLandscape(vp, x, y);
2366 if (v != nullptr) {
2367 Debug(misc, 2, "Vehicle {} (index {}) at {}", v->unitnumber, v->index, fmt::ptr(v));
2368 if (IsCompanyBuildableVehicleType(v)) {
2369 v = v->First();
2370 if (_ctrl_pressed && v->owner == _local_company) {
2371 StartStopVehicle(v, true);
2372 } else {
2373 ShowVehicleViewWindow(v);
2376 return true;
2378 return result;
2381 void RebuildViewportOverlay(Window *w)
2383 if (w->viewport->overlay != nullptr &&
2384 w->viewport->overlay->GetCompanyMask() != 0 &&
2385 w->viewport->overlay->GetCargoMask() != 0) {
2386 w->viewport->overlay->SetDirty();
2387 w->SetDirty();
2392 * Scrolls the viewport in a window to a given location.
2393 * @param x Desired x location of the map to scroll to (world coordinate).
2394 * @param y Desired y location of the map to scroll to (world coordinate).
2395 * @param z Desired z location of the map to scroll to (world coordinate). Use \c -1 to scroll to the height of the map at the \a x, \a y location.
2396 * @param w %Window containing the viewport.
2397 * @param instant Jump to the location instead of slowly moving to it.
2398 * @return Destination of the viewport was changed (to activate other actions when the viewport is already at the desired position).
2400 bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
2402 /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
2403 if (z == -1) {
2404 if ( x >= 0 && x <= (int)MapSizeX() * (int)TILE_SIZE - 1
2405 && y >= 0 && y <= (int)MapSizeY() * (int)TILE_SIZE - 1) {
2406 z = GetSlopePixelZ(x, y);
2407 } else {
2408 z = TileHeightOutsideMap(x / (int)TILE_SIZE, y / (int)TILE_SIZE);
2412 Point pt = MapXYZToViewport(w->viewport, x, y, z);
2413 w->viewport->follow_vehicle = INVALID_VEHICLE;
2415 if (w->viewport->dest_scrollpos_x == pt.x && w->viewport->dest_scrollpos_y == pt.y) return false;
2417 if (instant) {
2418 w->viewport->scrollpos_x = pt.x;
2419 w->viewport->scrollpos_y = pt.y;
2420 RebuildViewportOverlay(w);
2423 w->viewport->dest_scrollpos_x = pt.x;
2424 w->viewport->dest_scrollpos_y = pt.y;
2425 return true;
2429 * Scrolls the viewport in a window to a given location.
2430 * @param tile Desired tile to center on.
2431 * @param w %Window containing the viewport.
2432 * @param instant Jump to the location instead of slowly moving to it.
2433 * @return Destination of the viewport was changed (to activate other actions when the viewport is already at the desired position).
2435 bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
2437 return ScrollWindowTo(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, -1, w, instant);
2441 * Scrolls the viewport of the main window to a given location.
2442 * @param tile Desired tile to center on.
2443 * @param instant Jump to the location instead of slowly moving to it.
2444 * @return Destination of the viewport was changed (to activate other actions when the viewport is already at the desired position).
2446 bool ScrollMainWindowToTile(TileIndex tile, bool instant)
2448 return ScrollMainWindowTo(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, -1, instant);
2452 * Set a tile to display a red error square.
2453 * @param tile Tile that should show the red error square.
2455 void SetRedErrorSquare(TileIndex tile)
2457 TileIndex old;
2459 old = _thd.redsq;
2460 _thd.redsq = tile;
2462 if (tile != old) {
2463 if (tile != INVALID_TILE) MarkTileDirtyByTile(tile);
2464 if (old != INVALID_TILE) MarkTileDirtyByTile(old);
2469 * Highlight \a w by \a h tiles at the cursor.
2470 * @param w Width of the highlighted tiles rectangle.
2471 * @param h Height of the highlighted tiles rectangle.
2473 void SetTileSelectSize(int w, int h)
2475 _thd.new_size.x = w * TILE_SIZE;
2476 _thd.new_size.y = h * TILE_SIZE;
2477 _thd.new_outersize.x = 0;
2478 _thd.new_outersize.y = 0;
2481 void SetTileSelectBigSize(int ox, int oy, int sx, int sy)
2483 _thd.offs.x = ox * TILE_SIZE;
2484 _thd.offs.y = oy * TILE_SIZE;
2485 _thd.new_outersize.x = sx * TILE_SIZE;
2486 _thd.new_outersize.y = sy * TILE_SIZE;
2489 /** returns the best autorail highlight type from map coordinates */
2490 static HighLightStyle GetAutorailHT(int x, int y)
2492 return HT_RAIL | _autorail_piece[x & TILE_UNIT_MASK][y & TILE_UNIT_MASK];
2496 * Reset tile highlighting.
2498 void TileHighlightData::Reset()
2500 this->pos.x = 0;
2501 this->pos.y = 0;
2502 this->new_pos.x = 0;
2503 this->new_pos.y = 0;
2507 * Is the user dragging a 'diagonal rectangle'?
2508 * @return User is dragging a rotated rectangle.
2510 bool TileHighlightData::IsDraggingDiagonal()
2512 return (this->place_mode & HT_DIAGONAL) != 0 && _ctrl_pressed && _left_button_down;
2516 * Get the window that started the current highlighting.
2517 * @return The window that requested the current tile highlighting, or \c nullptr if not available.
2519 Window *TileHighlightData::GetCallbackWnd()
2521 return FindWindowById(this->window_class, this->window_number);
2527 * Updates tile highlighting for all cases.
2528 * Uses _thd.selstart and _thd.selend and _thd.place_mode (set elsewhere) to determine _thd.pos and _thd.size
2529 * Also drawstyle is determined. Uses _thd.new.* as a buffer and calls SetSelectionTilesDirty() twice,
2530 * Once for the old and once for the new selection.
2531 * _thd is TileHighlightData, found in viewport.h
2533 void UpdateTileSelection()
2535 int x1;
2536 int y1;
2538 if (_thd.freeze) return;
2540 HighLightStyle new_drawstyle = HT_NONE;
2541 bool new_diagonal = false;
2543 if ((_thd.place_mode & HT_DRAG_MASK) == HT_SPECIAL) {
2544 x1 = _thd.selend.x;
2545 y1 = _thd.selend.y;
2546 if (x1 != -1) {
2547 int x2 = _thd.selstart.x & ~TILE_UNIT_MASK;
2548 int y2 = _thd.selstart.y & ~TILE_UNIT_MASK;
2549 x1 &= ~TILE_UNIT_MASK;
2550 y1 &= ~TILE_UNIT_MASK;
2552 if (_thd.IsDraggingDiagonal()) {
2553 new_diagonal = true;
2554 } else {
2555 if (x1 >= x2) Swap(x1, x2);
2556 if (y1 >= y2) Swap(y1, y2);
2558 _thd.new_pos.x = x1;
2559 _thd.new_pos.y = y1;
2560 _thd.new_size.x = x2 - x1;
2561 _thd.new_size.y = y2 - y1;
2562 if (!new_diagonal) {
2563 _thd.new_size.x += TILE_SIZE;
2564 _thd.new_size.y += TILE_SIZE;
2566 new_drawstyle = _thd.next_drawstyle;
2568 } else if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
2569 Point pt = GetTileBelowCursor();
2570 x1 = pt.x;
2571 y1 = pt.y;
2572 if (x1 != -1) {
2573 switch (_thd.place_mode & HT_DRAG_MASK) {
2574 case HT_RECT:
2575 new_drawstyle = HT_RECT;
2576 break;
2577 case HT_POINT:
2578 new_drawstyle = HT_POINT;
2579 x1 += TILE_SIZE / 2;
2580 y1 += TILE_SIZE / 2;
2581 break;
2582 case HT_RAIL:
2583 /* Draw one highlighted tile in any direction */
2584 new_drawstyle = GetAutorailHT(pt.x, pt.y);
2585 break;
2586 case HT_LINE:
2587 switch (_thd.place_mode & HT_DIR_MASK) {
2588 case HT_DIR_X: new_drawstyle = HT_LINE | HT_DIR_X; break;
2589 case HT_DIR_Y: new_drawstyle = HT_LINE | HT_DIR_Y; break;
2591 case HT_DIR_HU:
2592 case HT_DIR_HL:
2593 new_drawstyle = (pt.x & TILE_UNIT_MASK) + (pt.y & TILE_UNIT_MASK) <= TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
2594 break;
2596 case HT_DIR_VL:
2597 case HT_DIR_VR:
2598 new_drawstyle = (pt.x & TILE_UNIT_MASK) > (pt.y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2599 break;
2601 default: NOT_REACHED();
2603 _thd.selstart.x = x1 & ~TILE_UNIT_MASK;
2604 _thd.selstart.y = y1 & ~TILE_UNIT_MASK;
2605 break;
2606 default:
2607 NOT_REACHED();
2609 _thd.new_pos.x = x1 & ~TILE_UNIT_MASK;
2610 _thd.new_pos.y = y1 & ~TILE_UNIT_MASK;
2614 /* redraw selection */
2615 if (_thd.drawstyle != new_drawstyle ||
2616 _thd.pos.x != _thd.new_pos.x || _thd.pos.y != _thd.new_pos.y ||
2617 _thd.size.x != _thd.new_size.x || _thd.size.y != _thd.new_size.y ||
2618 _thd.outersize.x != _thd.new_outersize.x ||
2619 _thd.outersize.y != _thd.new_outersize.y ||
2620 _thd.diagonal != new_diagonal) {
2621 /* Clear the old tile selection? */
2622 if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
2624 _thd.drawstyle = new_drawstyle;
2625 _thd.pos = _thd.new_pos;
2626 _thd.size = _thd.new_size;
2627 _thd.outersize = _thd.new_outersize;
2628 _thd.diagonal = new_diagonal;
2629 _thd.dirty = 0xff;
2631 /* Draw the new tile selection? */
2632 if ((new_drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
2637 * Displays the measurement tooltips when selecting multiple tiles
2638 * @param str String to be displayed
2639 * @param paramcount number of params to deal with
2640 * @param params (optional) up to 5 pieces of additional information that may be added to a tooltip
2641 * @param close_cond Condition for closing this tooltip.
2643 static inline void ShowMeasurementTooltips(StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_cond = TCC_EXIT_VIEWPORT)
2645 if (!_settings_client.gui.measure_tooltip) return;
2646 GuiShowTooltips(_thd.GetCallbackWnd(), str, paramcount, params, close_cond);
2649 static void HideMeasurementTooltips()
2651 CloseWindowById(WC_TOOLTIPS, 0);
2654 /** highlighting tiles while only going over them with the mouse */
2655 void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
2657 _thd.select_method = method;
2658 _thd.select_proc = process;
2659 _thd.selend.x = TileX(tile) * TILE_SIZE;
2660 _thd.selstart.x = TileX(tile) * TILE_SIZE;
2661 _thd.selend.y = TileY(tile) * TILE_SIZE;
2662 _thd.selstart.y = TileY(tile) * TILE_SIZE;
2664 /* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
2665 * In effect, placement starts from the centre of a tile
2667 if (method == VPM_X_OR_Y || method == VPM_FIX_X || method == VPM_FIX_Y) {
2668 _thd.selend.x += TILE_SIZE / 2;
2669 _thd.selend.y += TILE_SIZE / 2;
2670 _thd.selstart.x += TILE_SIZE / 2;
2671 _thd.selstart.y += TILE_SIZE / 2;
2674 HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
2675 if ((_thd.place_mode & HT_DRAG_MASK) == HT_RECT) {
2676 _thd.place_mode = HT_SPECIAL | others;
2677 _thd.next_drawstyle = HT_RECT | others;
2678 } else if (_thd.place_mode & (HT_RAIL | HT_LINE)) {
2679 _thd.place_mode = HT_SPECIAL | others;
2680 _thd.next_drawstyle = _thd.drawstyle | others;
2681 } else {
2682 _thd.place_mode = HT_SPECIAL | others;
2683 _thd.next_drawstyle = HT_POINT | others;
2685 _special_mouse_mode = WSM_SIZING;
2688 /** Drag over the map while holding the left mouse down. */
2689 void VpStartDragging(ViewportDragDropSelectionProcess process)
2691 _thd.select_method = VPM_X_AND_Y;
2692 _thd.select_proc = process;
2693 _thd.selstart.x = 0;
2694 _thd.selstart.y = 0;
2695 _thd.next_drawstyle = HT_RECT;
2697 _special_mouse_mode = WSM_DRAGGING;
2700 void VpSetPlaceSizingLimit(int limit)
2702 _thd.sizelimit = limit;
2706 * Highlights all tiles between a set of two tiles. Used in dock and tunnel placement
2707 * @param from TileIndex of the first tile to highlight
2708 * @param to TileIndex of the last tile to highlight
2710 void VpSetPresizeRange(TileIndex from, TileIndex to)
2712 uint64 distance = DistanceManhattan(from, to) + 1;
2714 _thd.selend.x = TileX(to) * TILE_SIZE;
2715 _thd.selend.y = TileY(to) * TILE_SIZE;
2716 _thd.selstart.x = TileX(from) * TILE_SIZE;
2717 _thd.selstart.y = TileY(from) * TILE_SIZE;
2718 _thd.next_drawstyle = HT_RECT;
2720 /* show measurement only if there is any length to speak of */
2721 if (distance > 1) {
2722 ShowMeasurementTooltips(STR_MEASURE_LENGTH, 1, &distance);
2723 } else {
2724 HideMeasurementTooltips();
2728 static void VpStartPreSizing()
2730 _thd.selend.x = -1;
2731 _special_mouse_mode = WSM_PRESIZE;
2735 * returns information about the 2x1 piece to be build.
2736 * The lower bits (0-3) are the track type.
2738 static HighLightStyle Check2x1AutoRail(int mode)
2740 int fxpy = _tile_fract_coords.x + _tile_fract_coords.y;
2741 int sxpy = (_thd.selend.x & TILE_UNIT_MASK) + (_thd.selend.y & TILE_UNIT_MASK);
2742 int fxmy = _tile_fract_coords.x - _tile_fract_coords.y;
2743 int sxmy = (_thd.selend.x & TILE_UNIT_MASK) - (_thd.selend.y & TILE_UNIT_MASK);
2745 switch (mode) {
2746 default: NOT_REACHED();
2747 case 0: // end piece is lower right
2748 if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
2749 if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
2750 return HT_DIR_Y;
2752 case 1:
2753 if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
2754 if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
2755 return HT_DIR_Y;
2757 case 2:
2758 if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
2759 if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
2760 return HT_DIR_X;
2762 case 3:
2763 if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
2764 if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
2765 return HT_DIR_X;
2770 * Check if the direction of start and end tile should be swapped based on
2771 * the dragging-style. Default directions are:
2772 * in the case of a line (HT_RAIL, HT_LINE): DIR_NE, DIR_NW, DIR_N, DIR_E
2773 * in the case of a rect (HT_RECT, HT_POINT): DIR_S, DIR_E
2774 * For example dragging a rectangle area from south to north should be swapped to
2775 * north-south (DIR_S) to obtain the same results with less code. This is what
2776 * the return value signifies.
2777 * @param style HighLightStyle dragging style
2778 * @param start_tile start tile of drag
2779 * @param end_tile end tile of drag
2780 * @return boolean value which when true means start/end should be swapped
2782 static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
2784 uint start_x = TileX(start_tile);
2785 uint start_y = TileY(start_tile);
2786 uint end_x = TileX(end_tile);
2787 uint end_y = TileY(end_tile);
2789 switch (style & HT_DRAG_MASK) {
2790 case HT_RAIL:
2791 case HT_LINE: return (end_x > start_x || (end_x == start_x && end_y > start_y));
2793 case HT_RECT:
2794 case HT_POINT: return (end_x != start_x && end_y < start_y);
2795 default: NOT_REACHED();
2798 return false;
2802 * Calculates height difference between one tile and another.
2803 * Multiplies the result to suit the standard given by #TILE_HEIGHT_STEP.
2805 * To correctly get the height difference we need the direction we are dragging
2806 * in, as well as with what kind of tool we are dragging. For example a horizontal
2807 * autorail tool that starts in bottom and ends at the top of a tile will need the
2808 * maximum of SW, S and SE, N corners respectively. This is handled by the lookup table below
2809 * See #_tileoffs_by_dir in map.cpp for the direction enums if you can't figure out the values yourself.
2810 * @param style Highlighting style of the drag. This includes direction and style (autorail, rect, etc.)
2811 * @param distance Number of tiles dragged, important for horizontal/vertical drags, ignored for others.
2812 * @param start_tile Start tile of the drag operation.
2813 * @param end_tile End tile of the drag operation.
2814 * @return Height difference between two tiles. The tile measurement tool utilizes this value in its tooltip.
2816 static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
2818 bool swap = SwapDirection(style, start_tile, end_tile);
2819 uint h0, h1; // Start height and end height.
2821 if (start_tile == end_tile) return 0;
2822 if (swap) Swap(start_tile, end_tile);
2824 switch (style & HT_DRAG_MASK) {
2825 case HT_RECT: {
2826 static const TileIndexDiffC heightdiff_area_by_dir[] = {
2827 /* Start */ {1, 0}, /* Dragging east */ {0, 0}, // Dragging south
2828 /* End */ {0, 1}, /* Dragging east */ {1, 1} // Dragging south
2831 /* In the case of an area we can determine whether we were dragging south or
2832 * east by checking the X-coordinates of the tiles */
2833 byte style_t = (byte)(TileX(end_tile) > TileX(start_tile));
2834 start_tile = TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_area_by_dir[style_t]));
2835 end_tile = TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_area_by_dir[2 + style_t]));
2836 FALLTHROUGH;
2839 case HT_POINT:
2840 h0 = TileHeight(start_tile);
2841 h1 = TileHeight(end_tile);
2842 break;
2843 default: { // All other types, this is mostly only line/autorail
2844 static const HighLightStyle flip_style_direction[] = {
2845 HT_DIR_X, HT_DIR_Y, HT_DIR_HL, HT_DIR_HU, HT_DIR_VR, HT_DIR_VL
2847 static const TileIndexDiffC heightdiff_line_by_dir[] = {
2848 /* Start */ {1, 0}, {1, 1}, /* HT_DIR_X */ {0, 1}, {1, 1}, // HT_DIR_Y
2849 /* Start */ {1, 0}, {0, 0}, /* HT_DIR_HU */ {1, 0}, {1, 1}, // HT_DIR_HL
2850 /* Start */ {1, 0}, {1, 1}, /* HT_DIR_VL */ {0, 1}, {1, 1}, // HT_DIR_VR
2852 /* Start */ {0, 1}, {0, 0}, /* HT_DIR_X */ {1, 0}, {0, 0}, // HT_DIR_Y
2853 /* End */ {0, 1}, {0, 0}, /* HT_DIR_HU */ {1, 1}, {0, 1}, // HT_DIR_HL
2854 /* End */ {1, 0}, {0, 0}, /* HT_DIR_VL */ {0, 0}, {0, 1}, // HT_DIR_VR
2857 distance %= 2; // we're only interested if the distance is even or uneven
2858 style &= HT_DIR_MASK;
2860 /* To handle autorail, we do some magic to be able to use a lookup table.
2861 * Firstly if we drag the other way around, we switch start&end, and if needed
2862 * also flip the drag-position. Eg if it was on the left, and the distance is even
2863 * that means the end, which is now the start is on the right */
2864 if (swap && distance == 0) style = flip_style_direction[style];
2866 /* Use lookup table for start-tile based on HighLightStyle direction */
2867 byte style_t = style * 2;
2868 assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
2869 h0 = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t])));
2870 uint ht = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t + 1])));
2871 h0 = std::max(h0, ht);
2873 /* Use lookup table for end-tile based on HighLightStyle direction
2874 * flip around side (lower/upper, left/right) based on distance */
2875 if (distance == 0) style_t = flip_style_direction[style] * 2;
2876 assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
2877 h1 = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t])));
2878 ht = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t + 1])));
2879 h1 = std::max(h1, ht);
2880 break;
2884 if (swap) Swap(h0, h1);
2885 return (int)(h1 - h0) * TILE_HEIGHT_STEP;
2888 static const StringID measure_strings_length[] = {STR_NULL, STR_MEASURE_LENGTH, STR_MEASURE_LENGTH_HEIGHTDIFF};
2891 * Check for underflowing the map.
2892 * @param test the variable to test for underflowing
2893 * @param other the other variable to update to keep the line
2894 * @param mult the constant to multiply the difference by for \c other
2896 static void CheckUnderflow(int &test, int &other, int mult)
2898 if (test >= 0) return;
2900 other += mult * test;
2901 test = 0;
2905 * Check for overflowing the map.
2906 * @param test the variable to test for overflowing
2907 * @param other the other variable to update to keep the line
2908 * @param max the maximum value for the \c test variable
2909 * @param mult the constant to multiply the difference by for \c other
2911 static void CheckOverflow(int &test, int &other, int max, int mult)
2913 if (test <= max) return;
2915 other += mult * (test - max);
2916 test = max;
2919 /** while dragging */
2920 static void CalcRaildirsDrawstyle(int x, int y, int method)
2922 HighLightStyle b;
2924 int dx = _thd.selstart.x - (_thd.selend.x & ~TILE_UNIT_MASK);
2925 int dy = _thd.selstart.y - (_thd.selend.y & ~TILE_UNIT_MASK);
2926 uint w = abs(dx) + TILE_SIZE;
2927 uint h = abs(dy) + TILE_SIZE;
2929 if (method & ~(VPM_RAILDIRS | VPM_SIGNALDIRS)) {
2930 /* We 'force' a selection direction; first four rail buttons. */
2931 method &= ~(VPM_RAILDIRS | VPM_SIGNALDIRS);
2932 int raw_dx = _thd.selstart.x - _thd.selend.x;
2933 int raw_dy = _thd.selstart.y - _thd.selend.y;
2934 switch (method) {
2935 case VPM_FIX_X:
2936 b = HT_LINE | HT_DIR_Y;
2937 x = _thd.selstart.x;
2938 break;
2940 case VPM_FIX_Y:
2941 b = HT_LINE | HT_DIR_X;
2942 y = _thd.selstart.y;
2943 break;
2945 case VPM_FIX_HORIZONTAL:
2946 if (dx == -dy) {
2947 /* We are on a straight horizontal line. Determine the 'rail'
2948 * to build based the sub tile location. */
2949 b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
2950 } else {
2951 /* We are not on a straight line. Determine the rail to build
2952 * based on whether we are above or below it. */
2953 b = dx + dy >= (int)TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
2955 /* Calculate where a horizontal line through the start point and
2956 * a vertical line from the selected end point intersect and
2957 * use that point as the end point. */
2958 int offset = (raw_dx - raw_dy) / 2;
2959 x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
2960 y = _thd.selstart.y + (offset & ~TILE_UNIT_MASK);
2962 /* 'Build' the last half rail tile if needed */
2963 if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
2964 if (dx + dy >= (int)TILE_SIZE) {
2965 x += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
2966 } else {
2967 y += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
2971 /* Make sure we do not overflow the map! */
2972 CheckUnderflow(x, y, 1);
2973 CheckUnderflow(y, x, 1);
2974 CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, 1);
2975 CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, 1);
2976 assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
2978 break;
2980 case VPM_FIX_VERTICAL:
2981 if (dx == dy) {
2982 /* We are on a straight vertical line. Determine the 'rail'
2983 * to build based the sub tile location. */
2984 b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2985 } else {
2986 /* We are not on a straight line. Determine the rail to build
2987 * based on whether we are left or right from it. */
2988 b = dx < dy ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2990 /* Calculate where a vertical line through the start point and
2991 * a horizontal line from the selected end point intersect and
2992 * use that point as the end point. */
2993 int offset = (raw_dx + raw_dy + (int)TILE_SIZE) / 2;
2994 x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
2995 y = _thd.selstart.y - (offset & ~TILE_UNIT_MASK);
2997 /* 'Build' the last half rail tile if needed */
2998 if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
2999 if (dx - dy < 0) {
3000 y += (dx > dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
3001 } else {
3002 x += (dx < dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
3006 /* Make sure we do not overflow the map! */
3007 CheckUnderflow(x, y, -1);
3008 CheckUnderflow(y, x, -1);
3009 CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, -1);
3010 CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, -1);
3011 assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
3013 break;
3015 default:
3016 NOT_REACHED();
3018 } else if (TileVirtXY(_thd.selstart.x, _thd.selstart.y) == TileVirtXY(x, y)) { // check if we're only within one tile
3019 if (method & VPM_RAILDIRS) {
3020 b = GetAutorailHT(x, y);
3021 } else { // rect for autosignals on one tile
3022 b = HT_RECT;
3024 } else if (h == TILE_SIZE) { // Is this in X direction?
3025 if (dx == (int)TILE_SIZE) { // 2x1 special handling
3026 b = (Check2x1AutoRail(3)) | HT_LINE;
3027 } else if (dx == -(int)TILE_SIZE) {
3028 b = (Check2x1AutoRail(2)) | HT_LINE;
3029 } else {
3030 b = HT_LINE | HT_DIR_X;
3032 y = _thd.selstart.y;
3033 } else if (w == TILE_SIZE) { // Or Y direction?
3034 if (dy == (int)TILE_SIZE) { // 2x1 special handling
3035 b = (Check2x1AutoRail(1)) | HT_LINE;
3036 } else if (dy == -(int)TILE_SIZE) { // 2x1 other direction
3037 b = (Check2x1AutoRail(0)) | HT_LINE;
3038 } else {
3039 b = HT_LINE | HT_DIR_Y;
3041 x = _thd.selstart.x;
3042 } else if (w > h * 2) { // still count as x dir?
3043 b = HT_LINE | HT_DIR_X;
3044 y = _thd.selstart.y;
3045 } else if (h > w * 2) { // still count as y dir?
3046 b = HT_LINE | HT_DIR_Y;
3047 x = _thd.selstart.x;
3048 } else { // complicated direction
3049 int d = w - h;
3050 _thd.selend.x = _thd.selend.x & ~TILE_UNIT_MASK;
3051 _thd.selend.y = _thd.selend.y & ~TILE_UNIT_MASK;
3053 /* four cases. */
3054 if (x > _thd.selstart.x) {
3055 if (y > _thd.selstart.y) {
3056 /* south */
3057 if (d == 0) {
3058 b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
3059 } else if (d >= 0) {
3060 x = _thd.selstart.x + h;
3061 b = HT_LINE | HT_DIR_VL;
3062 } else {
3063 y = _thd.selstart.y + w;
3064 b = HT_LINE | HT_DIR_VR;
3066 } else {
3067 /* west */
3068 if (d == 0) {
3069 b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
3070 } else if (d >= 0) {
3071 x = _thd.selstart.x + h;
3072 b = HT_LINE | HT_DIR_HL;
3073 } else {
3074 y = _thd.selstart.y - w;
3075 b = HT_LINE | HT_DIR_HU;
3078 } else {
3079 if (y > _thd.selstart.y) {
3080 /* east */
3081 if (d == 0) {
3082 b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
3083 } else if (d >= 0) {
3084 x = _thd.selstart.x - h;
3085 b = HT_LINE | HT_DIR_HU;
3086 } else {
3087 y = _thd.selstart.y + w;
3088 b = HT_LINE | HT_DIR_HL;
3090 } else {
3091 /* north */
3092 if (d == 0) {
3093 b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
3094 } else if (d >= 0) {
3095 x = _thd.selstart.x - h;
3096 b = HT_LINE | HT_DIR_VR;
3097 } else {
3098 y = _thd.selstart.y - w;
3099 b = HT_LINE | HT_DIR_VL;
3105 if (_settings_client.gui.measure_tooltip) {
3106 TileIndex t0 = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
3107 TileIndex t1 = TileVirtXY(x, y);
3108 uint distance = DistanceManhattan(t0, t1) + 1;
3109 byte index = 0;
3110 uint64 params[2];
3112 if (distance != 1) {
3113 int heightdiff = CalcHeightdiff(b, distance, t0, t1);
3114 /* If we are showing a tooltip for horizontal or vertical drags,
3115 * 2 tiles have a length of 1. To bias towards the ceiling we add
3116 * one before division. It feels more natural to count 3 lengths as 2 */
3117 if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
3118 distance = CeilDiv(distance, 2);
3121 params[index++] = distance;
3122 if (heightdiff != 0) params[index++] = heightdiff;
3125 ShowMeasurementTooltips(measure_strings_length[index], index, params);
3128 _thd.selend.x = x;
3129 _thd.selend.y = y;
3130 _thd.next_drawstyle = b;
3134 * Selects tiles while dragging
3135 * @param x X coordinate of end of selection
3136 * @param y Y coordinate of end of selection
3137 * @param method modifies the way tiles are selected. Possible
3138 * methods are VPM_* in viewport.h
3140 void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
3142 int sx, sy;
3143 HighLightStyle style;
3145 if (x == -1) {
3146 _thd.selend.x = -1;
3147 return;
3150 /* Special handling of drag in any (8-way) direction */
3151 if (method & (VPM_RAILDIRS | VPM_SIGNALDIRS)) {
3152 _thd.selend.x = x;
3153 _thd.selend.y = y;
3154 CalcRaildirsDrawstyle(x, y, method);
3155 return;
3158 /* Needed so level-land is placed correctly */
3159 if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_POINT) {
3160 x += TILE_SIZE / 2;
3161 y += TILE_SIZE / 2;
3164 sx = _thd.selstart.x;
3165 sy = _thd.selstart.y;
3167 int limit = 0;
3169 switch (method) {
3170 case VPM_X_OR_Y: // drag in X or Y direction
3171 if (abs(sy - y) < abs(sx - x)) {
3172 y = sy;
3173 style = HT_DIR_X;
3174 } else {
3175 x = sx;
3176 style = HT_DIR_Y;
3178 goto calc_heightdiff_single_direction;
3180 case VPM_X_LIMITED: // Drag in X direction (limited size).
3181 limit = (_thd.sizelimit - 1) * TILE_SIZE;
3182 FALLTHROUGH;
3184 case VPM_FIX_X: // drag in Y direction
3185 x = sx;
3186 style = HT_DIR_Y;
3187 goto calc_heightdiff_single_direction;
3189 case VPM_Y_LIMITED: // Drag in Y direction (limited size).
3190 limit = (_thd.sizelimit - 1) * TILE_SIZE;
3191 FALLTHROUGH;
3193 case VPM_FIX_Y: // drag in X direction
3194 y = sy;
3195 style = HT_DIR_X;
3197 calc_heightdiff_single_direction:;
3198 if (limit > 0) {
3199 x = sx + Clamp(x - sx, -limit, limit);
3200 y = sy + Clamp(y - sy, -limit, limit);
3202 if (_settings_client.gui.measure_tooltip) {
3203 TileIndex t0 = TileVirtXY(sx, sy);
3204 TileIndex t1 = TileVirtXY(x, y);
3205 uint distance = DistanceManhattan(t0, t1) + 1;
3206 byte index = 0;
3207 uint64 params[2];
3209 if (distance != 1) {
3210 /* With current code passing a HT_LINE style to calculate the height
3211 * difference is enough. However if/when a point-tool is created
3212 * with this method, function should be called with new_style (below)
3213 * instead of HT_LINE | style case HT_POINT is handled specially
3214 * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
3215 int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
3217 params[index++] = distance;
3218 if (heightdiff != 0) params[index++] = heightdiff;
3221 ShowMeasurementTooltips(measure_strings_length[index], index, params);
3223 break;
3225 case VPM_X_AND_Y_LIMITED: // Drag an X by Y constrained rect area.
3226 limit = (_thd.sizelimit - 1) * TILE_SIZE;
3227 x = sx + Clamp(x - sx, -limit, limit);
3228 y = sy + Clamp(y - sy, -limit, limit);
3229 FALLTHROUGH;
3231 case VPM_X_AND_Y: // drag an X by Y area
3232 if (_settings_client.gui.measure_tooltip) {
3233 static const StringID measure_strings_area[] = {
3234 STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
3237 TileIndex t0 = TileVirtXY(sx, sy);
3238 TileIndex t1 = TileVirtXY(x, y);
3239 uint dx = Delta(TileX(t0), TileX(t1)) + 1;
3240 uint dy = Delta(TileY(t0), TileY(t1)) + 1;
3241 byte index = 0;
3242 uint64 params[3];
3244 /* If dragging an area (eg dynamite tool) and it is actually a single
3245 * row/column, change the type to 'line' to get proper calculation for height */
3246 style = (HighLightStyle)_thd.next_drawstyle;
3247 if (_thd.IsDraggingDiagonal()) {
3248 /* Determine the "area" of the diagonal dragged selection.
3249 * We assume the area is the number of tiles along the X
3250 * edge and the number of tiles along the Y edge. However,
3251 * multiplying these two numbers does not give the exact
3252 * number of tiles; basically we are counting the black
3253 * squares on a chess board and ignore the white ones to
3254 * make the tile counts at the edges match up. There is no
3255 * other way to make a proper count though.
3257 * First convert to the rotated coordinate system. */
3258 int dist_x = TileX(t0) - TileX(t1);
3259 int dist_y = TileY(t0) - TileY(t1);
3260 int a_max = dist_x + dist_y;
3261 int b_max = dist_y - dist_x;
3263 /* Now determine the size along the edge, but due to the
3264 * chess board principle this counts double. */
3265 a_max = abs(a_max + (a_max > 0 ? 2 : -2)) / 2;
3266 b_max = abs(b_max + (b_max > 0 ? 2 : -2)) / 2;
3268 /* We get a 1x1 on normal 2x1 rectangles, due to it being
3269 * a seen as two sides. As the result for actual building
3270 * will be the same as non-diagonal dragging revert to that
3271 * behaviour to give it a more normally looking size. */
3272 if (a_max != 1 || b_max != 1) {
3273 dx = a_max;
3274 dy = b_max;
3276 } else if (style & HT_RECT) {
3277 if (dx == 1) {
3278 style = HT_LINE | HT_DIR_Y;
3279 } else if (dy == 1) {
3280 style = HT_LINE | HT_DIR_X;
3284 if (dx != 1 || dy != 1) {
3285 int heightdiff = CalcHeightdiff(style, 0, t0, t1);
3287 params[index++] = dx - (style & HT_POINT ? 1 : 0);
3288 params[index++] = dy - (style & HT_POINT ? 1 : 0);
3289 if (heightdiff != 0) params[index++] = heightdiff;
3292 ShowMeasurementTooltips(measure_strings_area[index], index, params);
3294 break;
3296 default: NOT_REACHED();
3299 _thd.selend.x = x;
3300 _thd.selend.y = y;
3304 * Handle the mouse while dragging for placement/resizing.
3305 * @return State of handling the event.
3307 EventState VpHandlePlaceSizingDrag()
3309 if (_special_mouse_mode != WSM_SIZING && _special_mouse_mode != WSM_DRAGGING) return ES_NOT_HANDLED;
3311 /* stop drag mode if the window has been closed */
3312 Window *w = _thd.GetCallbackWnd();
3313 if (w == nullptr) {
3314 ResetObjectToPlace();
3315 return ES_HANDLED;
3318 /* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
3319 if (_left_button_down) {
3320 if (_special_mouse_mode == WSM_DRAGGING) {
3321 /* Only register a drag event when the mouse moved. */
3322 if (_thd.new_pos.x == _thd.selstart.x && _thd.new_pos.y == _thd.selstart.y) return ES_HANDLED;
3323 _thd.selstart.x = _thd.new_pos.x;
3324 _thd.selstart.y = _thd.new_pos.y;
3327 w->OnPlaceDrag(_thd.select_method, _thd.select_proc, GetTileBelowCursor());
3328 return ES_HANDLED;
3331 /* Mouse button released. */
3332 _special_mouse_mode = WSM_NONE;
3333 if (_special_mouse_mode == WSM_DRAGGING) return ES_HANDLED;
3335 /* Keep the selected tool, but reset it to the original mode. */
3336 HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
3337 if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_RECT) {
3338 _thd.place_mode = HT_RECT | others;
3339 } else if (_thd.select_method & VPM_SIGNALDIRS) {
3340 _thd.place_mode = HT_RECT | others;
3341 } else if (_thd.select_method & VPM_RAILDIRS) {
3342 _thd.place_mode = (_thd.select_method & ~VPM_RAILDIRS) ? _thd.next_drawstyle : (HT_RAIL | others);
3343 } else {
3344 _thd.place_mode = HT_POINT | others;
3346 SetTileSelectSize(1, 1);
3348 HideMeasurementTooltips();
3349 w->OnPlaceMouseUp(_thd.select_method, _thd.select_proc, _thd.selend, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y));
3351 return ES_HANDLED;
3355 * Change the cursor and mouse click/drag handling to a mode for performing special operations like tile area selection, object placement, etc.
3356 * @param icon New shape of the mouse cursor.
3357 * @param pal Palette to use.
3358 * @param mode Mode to perform.
3359 * @param w %Window requesting the mode change.
3361 void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
3363 SetObjectToPlace(icon, pal, mode, w->window_class, w->window_number);
3366 #include "table/animcursors.h"
3369 * Change the cursor and mouse click/drag handling to a mode for performing special operations like tile area selection, object placement, etc.
3370 * @param icon New shape of the mouse cursor.
3371 * @param pal Palette to use.
3372 * @param mode Mode to perform.
3373 * @param window_class %Window class of the window requesting the mode change.
3374 * @param window_num Number of the window in its class requesting the mode change.
3376 void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
3378 if (_thd.window_class != WC_INVALID) {
3379 /* Undo clicking on button and drag & drop */
3380 Window *w = _thd.GetCallbackWnd();
3381 /* Call the abort function, but set the window class to something
3382 * that will never be used to avoid infinite loops. Setting it to
3383 * the 'next' window class must not be done because recursion into
3384 * this function might in some cases reset the newly set object to
3385 * place or not properly reset the original selection. */
3386 _thd.window_class = WC_INVALID;
3387 if (w != nullptr) {
3388 w->OnPlaceObjectAbort();
3389 HideMeasurementTooltips();
3393 /* Mark the old selection dirty, in case the selection shape or colour changes */
3394 if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
3396 SetTileSelectSize(1, 1);
3398 _thd.make_square_red = false;
3400 if (mode == HT_DRAG) { // HT_DRAG is for dragdropping trains in the depot window
3401 mode = HT_NONE;
3402 _special_mouse_mode = WSM_DRAGDROP;
3403 } else {
3404 _special_mouse_mode = WSM_NONE;
3407 _thd.place_mode = mode;
3408 _thd.window_class = window_class;
3409 _thd.window_number = window_num;
3411 if ((mode & HT_DRAG_MASK) == HT_SPECIAL) { // special tools, like tunnels or docks start with presizing mode
3412 VpStartPreSizing();
3415 if ((icon & ANIMCURSOR_FLAG) != 0) {
3416 SetAnimatedMouseCursor(_animcursors[icon & ~ANIMCURSOR_FLAG]);
3417 } else {
3418 SetMouseCursor(icon, pal);
3423 /** Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows). */
3424 void ResetObjectToPlace()
3426 SetObjectToPlace(SPR_CURSOR_MOUSE, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
3429 Point GetViewportStationMiddle(const Viewport *vp, const Station *st)
3431 int x = TileX(st->xy) * TILE_SIZE;
3432 int y = TileY(st->xy) * TILE_SIZE;
3433 int z = GetSlopePixelZ(Clamp(x, 0, MapSizeX() * TILE_SIZE - 1), Clamp(y, 0, MapSizeY() * TILE_SIZE - 1));
3435 Point p = RemapCoords(x, y, z);
3436 p.x = UnScaleByZoom(p.x - vp->virtual_left, vp->zoom) + vp->left;
3437 p.y = UnScaleByZoom(p.y - vp->virtual_top, vp->zoom) + vp->top;
3438 return p;
3441 /** Helper class for getting the best sprite sorter. */
3442 struct ViewportSSCSS {
3443 VpSorterChecker fct_checker; ///< The check function.
3444 VpSpriteSorter fct_sorter; ///< The sorting function.
3447 /** List of sorters ordered from best to worst. */
3448 static ViewportSSCSS _vp_sprite_sorters[] = {
3449 #ifdef WITH_SSE
3450 { &ViewportSortParentSpritesSSE41Checker, &ViewportSortParentSpritesSSE41 },
3451 #endif
3452 { &ViewportSortParentSpritesChecker, &ViewportSortParentSprites }
3455 /** Choose the "best" sprite sorter and set _vp_sprite_sorter. */
3456 void InitializeSpriteSorter()
3458 for (uint i = 0; i < lengthof(_vp_sprite_sorters); i++) {
3459 if (_vp_sprite_sorters[i].fct_checker()) {
3460 _vp_sprite_sorter = _vp_sprite_sorters[i].fct_sorter;
3461 break;
3464 assert(_vp_sprite_sorter != nullptr);
3468 * Scroll players main viewport.
3469 * @param flags type of operation
3470 * @param tile tile to center viewport on
3471 * @param target ViewportScrollTarget of scroll target
3472 * @param ref company or client id depending on the target
3473 * @return the cost of this operation or an error
3475 CommandCost CmdScrollViewport(DoCommandFlag flags, TileIndex tile, ViewportScrollTarget target, uint32 ref)
3477 if (_current_company != OWNER_DEITY) return CMD_ERROR;
3478 switch (target) {
3479 case VST_EVERYONE:
3480 break;
3481 case VST_COMPANY:
3482 if (_local_company != (CompanyID)ref) return CommandCost();
3483 break;
3484 case VST_CLIENT:
3485 if (_network_own_client_id != (ClientID)ref) return CommandCost();
3486 break;
3487 default:
3488 return CMD_ERROR;
3491 if (flags & DC_EXEC) {
3492 ResetObjectToPlace();
3493 ScrollMainWindowToTile(tile);
3495 return CommandCost();
3498 void MarkCatchmentTilesDirty()
3500 if (_viewport_highlight_town != nullptr) {
3501 MarkWholeScreenDirty();
3502 return;
3504 if (_viewport_highlight_station != nullptr) {
3505 if (_viewport_highlight_station->catchment_tiles.tile == INVALID_TILE) {
3506 MarkWholeScreenDirty();
3507 _viewport_highlight_station = nullptr;
3508 } else {
3509 BitmapTileIterator it(_viewport_highlight_station->catchment_tiles);
3510 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3511 MarkTileDirtyByTile(tile);
3518 * Select or deselect station for coverage area highlight.
3519 * Selecting a station will deselect a town.
3520 * @param *st Station in question
3521 * @param sel Select or deselect given station
3523 void SetViewportCatchmentStation(const Station *st, bool sel)
3525 if (_viewport_highlight_station != nullptr) SetWindowDirty(WC_STATION_VIEW, _viewport_highlight_station->index);
3526 if (_viewport_highlight_town != nullptr) SetWindowDirty(WC_TOWN_VIEW, _viewport_highlight_town->index);
3527 if (sel && _viewport_highlight_station != st) {
3528 MarkCatchmentTilesDirty();
3529 _viewport_highlight_station = st;
3530 _viewport_highlight_town = nullptr;
3531 MarkCatchmentTilesDirty();
3532 } else if (!sel && _viewport_highlight_station == st) {
3533 MarkCatchmentTilesDirty();
3534 _viewport_highlight_station = nullptr;
3536 if (_viewport_highlight_station != nullptr) SetWindowDirty(WC_STATION_VIEW, _viewport_highlight_station->index);
3540 * Select or deselect town for coverage area highlight.
3541 * Selecting a town will deselect a station.
3542 * @param *t Town in question
3543 * @param sel Select or deselect given town
3545 void SetViewportCatchmentTown(const Town *t, bool sel)
3547 if (_viewport_highlight_town != nullptr) SetWindowDirty(WC_TOWN_VIEW, _viewport_highlight_town->index);
3548 if (_viewport_highlight_station != nullptr) SetWindowDirty(WC_STATION_VIEW, _viewport_highlight_station->index);
3549 if (sel && _viewport_highlight_town != t) {
3550 _viewport_highlight_station = nullptr;
3551 _viewport_highlight_town = t;
3552 MarkWholeScreenDirty();
3553 } else if (!sel && _viewport_highlight_town == t) {
3554 _viewport_highlight_town = nullptr;
3555 MarkWholeScreenDirty();
3557 if (_viewport_highlight_town != nullptr) SetWindowDirty(WC_TOWN_VIEW, _viewport_highlight_town->index);