OpenTTD Source 20261112-master-gbcbec5e63f
viewport.cpp
Go to the documentation of this file.
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
26
62
63#include "stdafx.h"
64#include "core/backup_type.hpp"
65#include "landscape.h"
66#include "viewport_func.h"
67#include "station_base.h"
68#include "station_func.h"
69#include "waypoint_base.h"
70#include "town.h"
71#include "signs_base.h"
72#include "signs_func.h"
73#include "vehicle_base.h"
74#include "vehicle_gui.h"
75#include "blitter/factory.hpp"
76#include "spritecache.h"
77#include "strings_func.h"
78#include "zoom_func.h"
79#include "vehicle_func.h"
80#include "company_func.h"
81#include "waypoint_func.h"
82#include "window_func.h"
83#include "tilehighlight_func.h"
84#include "window_gui.h"
86#include "viewport_kdtree.h"
87#include "town_kdtree.h"
89#include "bridge_map.h"
90#include "command_func.h"
92#include "framerate_type.h"
93#include "viewport_cmd.h"
94
95#include <forward_list>
96#include <stack>
97
99
100#include "table/strings.h"
101#include "table/string_colours.h"
102
103#include "safeguards.h"
104
105Point _tile_fract_coords;
106
107
108ViewportSignKdtree _viewport_sign_kdtree{};
109static int _viewport_sign_maxwidth = 0;
110
111
112static const int MAX_TILE_EXTENT_LEFT = ZOOM_BASE * TILE_PIXELS;
113static const int MAX_TILE_EXTENT_RIGHT = ZOOM_BASE * TILE_PIXELS;
114static const int MAX_TILE_EXTENT_TOP = ZOOM_BASE * MAX_BUILDING_PIXELS;
115static const int MAX_TILE_EXTENT_BOTTOM = ZOOM_BASE * (TILE_PIXELS + 2 * TILE_HEIGHT);
116
118 std::string string;
119 uint16_t width;
120 Colours colour;
122 int32_t x;
123 int32_t y;
124};
125
127 SpriteID image;
128 PaletteID pal;
129 const SubSprite *sub;
130 int32_t x;
131 int32_t y;
132};
133
135 SpriteID image;
136 PaletteID pal;
137 const SubSprite *sub;
138 int32_t x;
139 int32_t y;
140 bool relative;
141 int next;
142};
143
145enum class FoundationPart : uint8_t {
146 None = 0xFF,
147 Normal = 0,
150};
151
156enum class SpriteCombineMode : uint8_t {
160};
161
162typedef std::vector<TileSpriteToDraw> TileSpriteToDrawVector;
163typedef std::vector<StringSpriteToDraw> StringSpriteToDrawVector;
164typedef std::vector<ParentSpriteToDraw> ParentSpriteToDrawVector;
165typedef std::vector<ChildScreenSpriteToDraw> ChildScreenSpriteToDrawVector;
166
167constexpr int LAST_CHILD_NONE = -1;
168constexpr int LAST_CHILD_PARENT = -2;
169
172 DrawPixelInfo dpi;
173
174 StringSpriteToDrawVector string_sprites_to_draw;
175 TileSpriteToDrawVector tile_sprites_to_draw;
176 ParentSpriteToDrawVector parent_sprites_to_draw;
177 ParentSpriteToSortVector parent_sprites_to_sort;
178 ChildScreenSpriteToDrawVector child_screen_sprites_to_draw;
179
180 int last_child;
181
183
188};
189
190static bool MarkViewportDirty(const Viewport &vp, int left, int top, int right, int bottom);
191
192static ViewportDrawer _vd;
193
195static TileInfo _cur_ti;
196bool _draw_bounding_boxes = false;
197bool _draw_dirty_blocks = false;
198uint _dirty_block_colour = 0;
199static VpSpriteSorter _vp_sprite_sorter = nullptr;
200
201static Point MapXYZToViewport(const Viewport &vp, int x, int y, int z)
202{
203 Point p = RemapCoords(x, y, z);
204 p.x -= vp.virtual_width / 2;
205 p.y -= vp.virtual_height / 2;
206 return p;
207}
208
219void InitializeWindowViewport(Window *w, int x, int y,
220 int width, int height, std::variant<TileIndex, VehicleID> focus, ZoomLevel zoom)
221{
222 assert(w->viewport == nullptr);
223
224 auto vp = std::make_unique<ViewportData>();
225
226 vp->left = x + w->left;
227 vp->top = y + w->top;
228 vp->width = width;
229 vp->height = height;
230
231 vp->zoom = Clamp(zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max);
232
233 vp->virtual_width = ScaleByZoom(width, zoom);
234 vp->virtual_height = ScaleByZoom(height, zoom);
235
236 Point pt;
237
238 if (std::holds_alternative<VehicleID>(focus)) {
239 const Vehicle *veh;
240
241 vp->follow_vehicle = std::get<VehicleID>(focus);
242 veh = Vehicle::Get(vp->follow_vehicle)->GetMovingFront();
243 pt = MapXYZToViewport(*vp, veh->x_pos, veh->y_pos, veh->z_pos);
244 } else {
245 TileIndex tile = std::get<TileIndex>(focus);
246 if (tile == INVALID_TILE) {
247 /* No tile? Use center of main viewport. */
248 const Window *mw = GetMainWindow();
249
250 /* center on same place as main window (zoom is maximum, no adjustment needed) */
251 pt.x = mw->viewport->scrollpos_x + mw->viewport->virtual_width / 2;
252 pt.x -= vp->virtual_width / 2;
253 pt.y = mw->viewport->scrollpos_y + mw->viewport->virtual_height / 2;
254 pt.y -= vp->virtual_height / 2;
255 } else {
256 x = TileX(tile) * TILE_SIZE;
257 y = TileY(tile) * TILE_SIZE;
258 pt = MapXYZToViewport(*vp, x, y, GetSlopePixelZ(x, y));
259 }
260 vp->follow_vehicle = VehicleID::Invalid();
261 }
262
263 vp->scrollpos_x = pt.x;
264 vp->scrollpos_y = pt.y;
265 vp->dest_scrollpos_x = pt.x;
266 vp->dest_scrollpos_y = pt.y;
267
268 vp->overlay = nullptr;
269
270 vp->virtual_left = 0;
271 vp->virtual_top = 0;
272
273 w->viewport = std::move(vp);
274}
275
276static Point _vp_move_offs;
277
278static void DoSetViewportPosition(Window::IteratorToFront it, int left, int top, int width, int height)
279{
280 for (; !it.IsEnd(); ++it) {
281 const Window *w = *it;
282 if (left + width > w->left &&
283 w->left + w->width > left &&
284 top + height > w->top &&
285 w->top + w->height > top) {
286
287 if (left < w->left) {
288 DoSetViewportPosition(it, left, top, w->left - left, height);
289 DoSetViewportPosition(it, left + (w->left - left), top, width - (w->left - left), height);
290 return;
291 }
292
293 if (left + width > w->left + w->width) {
294 DoSetViewportPosition(it, left, top, (w->left + w->width - left), height);
295 DoSetViewportPosition(it, left + (w->left + w->width - left), top, width - (w->left + w->width - left), height);
296 return;
297 }
298
299 if (top < w->top) {
300 DoSetViewportPosition(it, left, top, width, (w->top - top));
301 DoSetViewportPosition(it, left, top + (w->top - top), width, height - (w->top - top));
302 return;
303 }
304
305 if (top + height > w->top + w->height) {
306 DoSetViewportPosition(it, left, top, width, (w->top + w->height - top));
307 DoSetViewportPosition(it, left, top + (w->top + w->height - top), width, height - (w->top + w->height - top));
308 return;
309 }
310
311 return;
312 }
313 }
314
315 {
316 int xo = _vp_move_offs.x;
317 int yo = _vp_move_offs.y;
318
319 if (abs(xo) >= width || abs(yo) >= height) {
320 /* fully_outside */
321 RedrawScreenRect(left, top, left + width, top + height);
322 return;
323 }
324
325 GfxScroll(left, top, width, height, xo, yo);
326
327 if (xo > 0) {
328 RedrawScreenRect(left, top, xo + left, top + height);
329 left += xo;
330 width -= xo;
331 } else if (xo < 0) {
332 RedrawScreenRect(left + width + xo, top, left + width, top + height);
333 width += xo;
334 }
335
336 if (yo > 0) {
337 RedrawScreenRect(left, top, width + left, top + yo);
338 } else if (yo < 0) {
339 RedrawScreenRect(left, top + height + yo, width + left, top + height);
340 }
341 }
342}
343
344static void SetViewportPosition(Window *w, int x, int y)
345{
346 Viewport &vp = *w->viewport;
347 int old_left = vp.virtual_left;
348 int old_top = vp.virtual_top;
349 int i;
350 int left, top, width, height;
351
352 vp.virtual_left = x;
353 vp.virtual_top = y;
354
355 /* Viewport is bound to its left top corner, so it must be rounded down (UnScaleByZoomLower)
356 * else glitch described in FS#1412 will happen (offset by 1 pixel with zoom level > NORMAL)
357 */
358 old_left = UnScaleByZoomLower(old_left, vp.zoom);
359 old_top = UnScaleByZoomLower(old_top, vp.zoom);
360 x = UnScaleByZoomLower(x, vp.zoom);
361 y = UnScaleByZoomLower(y, vp.zoom);
362
363 old_left -= x;
364 old_top -= y;
365
366 if (old_top == 0 && old_left == 0) return;
367
368 _vp_move_offs.x = old_left;
369 _vp_move_offs.y = old_top;
370
371 left = vp.left;
372 top = vp.top;
373 width = vp.width;
374 height = vp.height;
375
376 if (left < 0) {
377 width += left;
378 left = 0;
379 }
380
381 i = left + width - _screen.width;
382 if (i >= 0) width -= i;
383
384 if (width > 0) {
385 if (top < 0) {
386 height += top;
387 top = 0;
388 }
389
390 i = top + height - _screen.height;
391 if (i >= 0) height -= i;
392
393 if (height > 0) {
395 ++it;
396 DoSetViewportPosition(it, left, top, width, height);
397 }
398 }
399}
400
409Viewport *IsPtInWindowViewport(const Window *w, int x, int y)
410{
411 if (w->viewport == nullptr) return nullptr;
412
413 const Viewport &vp = *w->viewport;
414 if (IsInsideMM(x, vp.left, vp.left + vp.width) && IsInsideMM(y, vp.top, vp.top + vp.height)) return w->viewport.get();
415
416 return nullptr;
417}
418
431Point TranslateXYToTileCoord(const Viewport &vp, int x, int y, bool clamp_to_map)
432{
433 if (!IsInsideBS(x, vp.left, vp.width) || !IsInsideBS(y, vp.top, vp.height)) {
434 Point pt = { -1, -1 };
435 return pt;
436 }
437
438 return InverseRemapCoords2(
439 ScaleByZoom(x - vp.left, vp.zoom) + vp.virtual_left,
440 ScaleByZoom(y - vp.top, vp.zoom) + vp.virtual_top, clamp_to_map);
441}
442
443/* When used for zooming, check area below current coordinates (x,y)
444 * and return the tile of the zoomed out/in position (zoom_x, zoom_y)
445 * when you just want the tile, make x = zoom_x and y = zoom_y */
446static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
447{
448 if (Window *w = FindWindowFromPt(x, y); w != nullptr) {
449 if (Viewport *vp = IsPtInWindowViewport(w, x, y); vp != nullptr) {
450 return TranslateXYToTileCoord(*vp, zoom_x, zoom_y);
451 }
452 }
453
454 return {-1, -1};
455}
456
457Point GetTileBelowCursor()
458{
459 return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, _cursor.pos.x, _cursor.pos.y);
460}
461
462
463Point GetTileZoomCenterWindow(bool in, Window * w)
464{
465 int x, y;
466 const Viewport &vp = *w->viewport;
467
468 if (in) {
469 x = ((_cursor.pos.x - vp.left) >> 1) + (vp.width >> 2);
470 y = ((_cursor.pos.y - vp.top) >> 1) + (vp.height >> 2);
471 } else {
472 x = vp.width - (_cursor.pos.x - vp.left);
473 y = vp.height - (_cursor.pos.y - vp.top);
474 }
475 /* Get the tile below the cursor and center on the zoomed-out center */
476 return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, x + vp.left, y + vp.top);
477}
478
487void HandleZoomMessage(Window *w, const Viewport &vp, WidgetID widget_zoom_in, WidgetID widget_zoom_out)
488{
489 w->SetWidgetDisabledState(widget_zoom_in, vp.zoom <= _settings_client.gui.zoom_min);
490 w->SetWidgetDirty(widget_zoom_in);
491
492 w->SetWidgetDisabledState(widget_zoom_out, vp.zoom >= _settings_client.gui.zoom_max);
493 w->SetWidgetDirty(widget_zoom_out);
494}
495
508static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32_t x, int32_t y, int z, const SubSprite *sub = nullptr, int extra_offs_x = 0, int extra_offs_y = 0)
509{
510 assert((image & SPRITE_MASK) < MAX_SPRITES);
511
512 TileSpriteToDraw &ts = _vd.tile_sprites_to_draw.emplace_back();
513 ts.image = image;
514 ts.pal = pal;
515 ts.sub = sub;
516 Point pt = RemapCoords(x, y, z);
517 ts.x = pt.x + extra_offs_x;
518 ts.y = pt.y + extra_offs_y;
519}
520
533static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
534{
535 assert(foundation_part < FoundationPart::End);
536 assert(_vd.foundation[foundation_part] != -1);
537 Point offs = _vd.foundation_offset[foundation_part];
538
539 /* Change the active ChildSprite list to the one of the foundation */
540 AutoRestoreBackup backup(_vd.last_child, _vd.last_foundation_child[foundation_part]);
541 AddChildSpriteScreen(image, pal, offs.x + extra_offs_x, offs.y + extra_offs_y, false, sub, false, false);
542}
543
557void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32_t x, int32_t y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
558{
559 /* Switch to first foundation part, if no foundation was drawn */
560 if (_vd.foundation_part == FoundationPart::None) _vd.foundation_part = FoundationPart::Normal;
561
562 if (_vd.foundation[_vd.foundation_part] != -1) {
563 Point pt = RemapCoords(x, y, z);
564 AddChildSpriteToFoundation(image, pal, sub, _vd.foundation_part, pt.x + extra_offs_x * ZOOM_BASE, pt.y + extra_offs_y * ZOOM_BASE);
565 } else {
566 AddTileSpriteToDraw(image, pal, _cur_ti.x + x, _cur_ti.y + y, _cur_ti.z + z, sub, extra_offs_x * ZOOM_BASE, extra_offs_y * ZOOM_BASE);
567 }
568}
569
580void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
581{
582 DrawGroundSpriteAt(image, pal, 0, 0, 0, sub, extra_offs_x, extra_offs_y);
583}
584
591{
592 switch (foundation_part) {
595 default: NOT_REACHED();
596 }
597}
598
606void OffsetGroundSprite(int x, int y)
607{
608 /* Switch to next foundation part */
609 _vd.foundation_part = GetNextFoundationPart(_vd.foundation_part);
610
611 /* _vd.last_child is LAST_CHILD_NONE if foundation sprite was clipped by the viewport bounds */
612 if (_vd.last_child != LAST_CHILD_NONE) _vd.foundation[_vd.foundation_part] = static_cast<uint>(_vd.parent_sprites_to_draw.size()) - 1;
613
614 _vd.foundation_offset[_vd.foundation_part].x = x * ZOOM_BASE;
615 _vd.foundation_offset[_vd.foundation_part].y = y * ZOOM_BASE;
616 _vd.last_foundation_child[_vd.foundation_part] = _vd.last_child;
617}
618
630static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, int z, const SubSprite *sub)
631{
632 Point pt = RemapCoords(x, y, z);
633 const Sprite *spr = GetSprite(image & SPRITE_MASK, SpriteType::Normal);
634
635 if (pt.x + spr->x_offs >= _vd.dpi.left + _vd.dpi.width ||
636 pt.x + spr->x_offs + spr->width <= _vd.dpi.left ||
637 pt.y + spr->y_offs >= _vd.dpi.top + _vd.dpi.height ||
638 pt.y + spr->y_offs + spr->height <= _vd.dpi.top)
639 return;
640
641 const ParentSpriteToDraw &pstd = _vd.parent_sprites_to_draw.back();
642 AddChildSpriteScreen(image, pal, pt.x - pstd.left, pt.y - pstd.top, false, sub, false);
643}
644
665void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int z, const SpriteBounds &bounds, bool transparent, const SubSprite *sub)
666{
667 int32_t left, right, top, bottom;
668
669 assert((image & SPRITE_MASK) < MAX_SPRITES);
670
671 /* Move to bounding box. */
672 x += bounds.origin.x;
673 y += bounds.origin.y;
674 z += bounds.origin.z;
675
676 /* make the sprites transparent with the right palette */
677 if (transparent) {
680 }
681
682 if (_vd.combine_sprites == SpriteCombineMode::Active) {
683 AddCombinedSprite(image, pal, x + bounds.offset.x, y + bounds.offset.y, z + bounds.offset.z, sub);
684 return;
685 }
686
687 _vd.last_child = LAST_CHILD_NONE;
688
689 Point pt = RemapCoords(x + bounds.offset.x, y + bounds.offset.y, z + bounds.offset.z);
690 int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
691
692 /* Compute screen extents of sprite */
693 if (image == SPR_EMPTY_BOUNDING_BOX) {
694 left = tmp_left = RemapCoords(x + bounds.extent.x, y, z).x;
695 right = RemapCoords(x, y + bounds.extent.y, z).x + 1;
696 top = tmp_top = RemapCoords(x, y, z + bounds.extent.z).y;
697 bottom = RemapCoords(x + bounds.extent.x, y + bounds.extent.y, z).y + 1;
698 } else {
699 const Sprite *spr = GetSprite(image & SPRITE_MASK, SpriteType::Normal);
700 left = tmp_left = (pt.x += spr->x_offs);
701 right = (pt.x + spr->width );
702 top = tmp_top = (pt.y += spr->y_offs);
703 bottom = (pt.y + spr->height);
704 }
705
706 if (_draw_bounding_boxes && (image != SPR_EMPTY_BOUNDING_BOX)) {
707 /* Compute maximal extents of sprite and its bounding box */
708 left = std::min(left , RemapCoords(x + bounds.extent.x, y, z).x);
709 right = std::max(right , RemapCoords(x, y + bounds.extent.y, z).x + 1);
710 top = std::min(top , RemapCoords(x, y, z + bounds.extent.z).y);
711 bottom = std::max(bottom, RemapCoords(x + bounds.extent.x, y + bounds.extent.y, z).y + 1);
712 }
713
714 /* Do not add the sprite to the viewport, if it is outside */
715 if (left >= _vd.dpi.left + _vd.dpi.width ||
716 right <= _vd.dpi.left ||
717 top >= _vd.dpi.top + _vd.dpi.height ||
718 bottom <= _vd.dpi.top) {
719 return;
720 }
721
722 ParentSpriteToDraw &ps = _vd.parent_sprites_to_draw.emplace_back();
723 ps.x = tmp_x;
724 ps.y = tmp_y;
725
726 ps.left = tmp_left;
727 ps.top = tmp_top;
728
729 ps.image = image;
730 ps.pal = pal;
731 ps.sub = sub;
732 ps.xmin = x;
733 ps.xmax = x + bounds.extent.x - 1;
734
735 ps.ymin = y;
736 ps.ymax = y + bounds.extent.y - 1;
737
738 ps.zmin = z;
739 ps.zmax = z + bounds.extent.z - 1;
740
742
743 _vd.last_child = LAST_CHILD_PARENT;
744
745 if (_vd.combine_sprites == SpriteCombineMode::Pending) _vd.combine_sprites = SpriteCombineMode::Active;
746}
747
767{
768 assert(_vd.combine_sprites == SpriteCombineMode::None);
769 _vd.combine_sprites = SpriteCombineMode::Pending;
770}
771
777{
778 assert(_vd.combine_sprites != SpriteCombineMode::None);
779 _vd.combine_sprites = SpriteCombineMode::None;
780}
781
792static bool IsInRangeInclusive(int begin, int end, int check)
793{
794 if (begin > end) std::swap(begin, end);
795 return begin <= check && check <= end;
796}
797
804bool IsInsideRotatedRectangle(int x, int y)
805{
806 int dist_a = (_thd.size.x + _thd.size.y); // Rotated coordinate system for selected rectangle.
807 int dist_b = (_thd.size.x - _thd.size.y); // We don't have to divide by 2. It's all relative!
808 int a = ((x - _thd.pos.x) + (y - _thd.pos.y)); // Rotated coordinate system for the point under scrutiny.
809 int b = ((x - _thd.pos.x) - (y - _thd.pos.y));
810
811 /* Check if a and b are between 0 and dist_a or dist_b respectively. */
812 return IsInRangeInclusive(dist_a, 0, a) && IsInRangeInclusive(dist_b, 0, b);
813}
814
827void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale, bool relative)
828{
829 assert((image & SPRITE_MASK) < MAX_SPRITES);
830
831 /* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
832 if (_vd.last_child == LAST_CHILD_NONE) return;
833
834 /* make the sprites transparent with the right palette */
835 if (transparent) {
838 }
839
840 int32_t child_id = static_cast<int32_t>(_vd.child_screen_sprites_to_draw.size());
841 if (_vd.last_child != LAST_CHILD_PARENT) {
842 _vd.child_screen_sprites_to_draw[_vd.last_child].next = child_id;
843 } else {
844 _vd.parent_sprites_to_draw.back().first_child = child_id;
845 }
846
847 ChildScreenSpriteToDraw &cs = _vd.child_screen_sprites_to_draw.emplace_back();
848 cs.image = image;
849 cs.pal = pal;
850 cs.sub = sub;
851 cs.x = scale ? x * ZOOM_BASE : x;
852 cs.y = scale ? y * ZOOM_BASE : y;
853 cs.relative = relative;
855
856 /* Append the sprite to the active ChildSprite list.
857 * If the active ParentSprite is a foundation, update last_foundation_child as well.
858 * Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
859 if (_vd.last_foundation_child[FoundationPart::Normal] == _vd.last_child) _vd.last_foundation_child[FoundationPart::Normal] = child_id;
860 if (_vd.last_foundation_child[FoundationPart::Halftile] == _vd.last_child) _vd.last_foundation_child[FoundationPart::Halftile] = child_id;
861 _vd.last_child = child_id;
862}
863
873static std::string &AddStringToDraw(int x, int y, Colours colour, ViewportStringFlags flags, uint16_t width)
874{
875 assert(width != 0);
876 StringSpriteToDraw &ss = _vd.string_sprites_to_draw.emplace_back();
877 ss.colour = colour;
878 ss.flags = flags;
879 ss.x = x;
880 ss.y = y;
881 ss.width = width;
882
883 return ss.string;
884}
885
886
900static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part, int extra_offs_x = 0, int extra_offs_y = 0)
901{
902 if (_vd.foundation[foundation_part] == -1) {
903 /* draw on real ground */
904 AddTileSpriteToDraw(image, pal, ti->x, ti->y, ti->z + z_offset, nullptr, extra_offs_x, extra_offs_y);
905 } else {
906 /* draw on top of foundation */
907 AddChildSpriteToFoundation(image, pal, nullptr, foundation_part, extra_offs_x, extra_offs_y - z_offset * ZOOM_BASE);
908 }
909}
910
917static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
918{
919 if (!IsValidTile(ti->tile)) return;
920
921 SpriteID sel;
922 if (IsHalftileSlope(ti->tileh)) {
923 Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
924 SpriteID sel2 = SPR_HALFTILE_SELECTION_FLAT + to_underlying(halftile_corner);
926
927 Corner opposite_corner = OppositeCorner(halftile_corner);
928 if (IsSteepSlope(ti->tileh)) {
930 } else {
932 }
933 sel += to_underlying(opposite_corner);
934 } else {
935 sel = SPR_SELECT_TILE + SlopeToSpriteOffset(ti->tileh);
936 }
938}
939
940static bool IsPartOfAutoLine(int px, int py)
941{
942 px -= _thd.selstart.x;
943 py -= _thd.selstart.y;
944
945 if ((_thd.drawstyle & HT_DRAG_MASK) != HT_LINE) return false;
946
947 switch (_thd.drawstyle & HT_DIR_MASK) {
948 case HT_DIR_X: return py == 0; // x direction
949 case HT_DIR_Y: return px == 0; // y direction
950 case HT_DIR_HU: return px == -py || px == -py - 16; // horizontal upper
951 case HT_DIR_HL: return px == -py || px == -py + 16; // horizontal lower
952 case HT_DIR_VL: return px == py || px == py + 16; // vertical left
953 case HT_DIR_VR: return px == py || px == py - 16; // vertical right
954 default:
955 NOT_REACHED();
956 }
957}
958
959/* [direction][side] */
960static const HighLightStyle _autorail_type[6][2] = {
961 { HT_DIR_X, HT_DIR_X },
962 { HT_DIR_Y, HT_DIR_Y },
963 { HT_DIR_HU, HT_DIR_HL },
964 { HT_DIR_HL, HT_DIR_HU },
965 { HT_DIR_VL, HT_DIR_VR },
967};
968
969#include "table/autorail.h"
970
977static void DrawAutorailSelection(const TileInfo *ti, HighLightStyle highlight_style)
978{
979 SpriteID image;
980 PaletteID pal;
981
982 FoundationPart foundation_part = FoundationPart::Normal;
983 Slope slope = RemoveHalftileSlope(ti->tileh);
984 if (IsHalftileSlope(ti->tileh)) {
986 Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
987 if ((highlight_style & HT_DIR_MASK) != lower_rail[halftile_corner]) {
988 foundation_part = FoundationPart::Halftile;
989 /* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
990 slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
991 }
992 }
993
994 int offset = _autorail_slope_sprite_offsets[slope][highlight_style & HT_DIR_MASK];
995 if (offset >= 0) {
996 image = SPR_AUTORAIL_BASE + offset;
997 pal = PAL_NONE;
998 } else {
999 image = SPR_AUTORAIL_BASE - offset;
1001 }
1002
1003 DrawSelectionSprite(image, _thd.make_square_red ? PALETTE_SEL_TILE_RED : pal, ti, 7, foundation_part);
1004}
1005
1007enum class TileHighlightType : uint8_t {
1012};
1013
1019
1026{
1027 if (_viewport_highlight_station != nullptr) {
1029 if (_viewport_highlight_station->TileIsInCatchment(t)) return TileHighlightType::Blue;
1030 }
1031
1032 if (_viewport_highlight_station_rect != nullptr) {
1034 if (_viewport_highlight_station_rect->spread.Contains(t)) return TileHighlightType::Blue;
1035 }
1036
1037 if (_viewport_highlight_waypoint != nullptr) {
1039 }
1040
1041 if (_viewport_highlight_waypoint_rect != nullptr) {
1043 if (_viewport_highlight_waypoint_rect->spread.Contains(t)) return TileHighlightType::Blue;
1044 }
1045
1046 if (_viewport_highlight_town != nullptr) {
1047 if (IsTileType(t, TileType::House)) {
1048 if (GetTownIndex(t) == _viewport_highlight_town->index) {
1049 for (const Station *st : _viewport_highlight_town->stations_near) {
1050 if (st->owner != _current_company) continue;
1051 if (st->TileIsInCatchment(t)) return TileHighlightType::Blue;
1052 }
1054 }
1055 } else if (IsTileType(t, TileType::Station)) {
1056 for (const Station *st : _viewport_highlight_town->stations_near) {
1057 if (st->owner != _current_company) continue;
1058 if (GetStationIndex(t) == st->index) return TileHighlightType::White;
1059 }
1060 }
1061 }
1062
1064}
1065
1072{
1073 switch (tht) {
1074 default:
1075 case TileHighlightType::None: break;
1076 case TileHighlightType::White: DrawTileSelectionRect(ti, PAL_NONE); break;
1079 }
1080}
1081
1087{
1088 /* Going through cases in order of computational time. */
1089
1090 if (_town_local_authority_kdtree.Count() == 0) return;
1091
1092 /* Tile belongs to town regardless of distance from town. */
1093 if (GetTileType(ti->tile) == TileType::House) {
1094 if (!Town::GetByTile(ti->tile)->show_zone) return;
1095
1097 return;
1098 }
1099
1100 /* If the closest town in the highlighted list is far, we can stop searching. */
1101 TownID tid = _town_local_authority_kdtree.FindNearest(TileX(ti->tile), TileY(ti->tile));
1102 Town *closest_highlighted_town = Town::Get(tid);
1103
1104 if (DistanceManhattan(ti->tile, closest_highlighted_town->xy) >= _settings_game.economy.dist_local_authority) return;
1105
1106 /* Tile is inside of the local autrhority distance of a highlighted town,
1107 but it is possible that a non-highlighted town is even closer. */
1108 Town *closest_town = ClosestTownFromTile(ti->tile, _settings_game.economy.dist_local_authority);
1109
1110 if (closest_town->show_zone) {
1112 }
1113
1114}
1115
1120static void DrawTileSelection(const TileInfo *ti)
1121{
1122 /* Highlight tiles inside local authority of selected towns. */
1124
1125 /* Draw a red error square? */
1126 bool is_redsq = _thd.redsq == ti->tile;
1128
1130 DrawTileHighlightType(ti, tht);
1131
1132 /* No tile selection active? */
1133 if ((_thd.drawstyle & HT_DRAG_MASK) == HT_NONE) return;
1134
1135 if (_thd.diagonal) { // We're drawing a 45 degrees rotated (diagonal) rectangle
1136 if (IsInsideRotatedRectangle((int)ti->x, (int)ti->y)) goto draw_inner;
1137 return;
1138 }
1139
1140 /* Inside the inner area? */
1141 if (IsInsideBS(ti->x, _thd.pos.x, _thd.size.x) &&
1142 IsInsideBS(ti->y, _thd.pos.y, _thd.size.y)) {
1143draw_inner:
1144 if (_thd.drawstyle & HT_RECT) {
1145 if (!is_redsq) DrawTileSelectionRect(ti, _thd.make_square_red ? PALETTE_SEL_TILE_RED : PAL_NONE);
1146 } else if (_thd.drawstyle & HT_POINT) {
1147 /* Figure out the Z coordinate for the single dot. */
1148 int z = 0;
1149 FoundationPart foundation_part = FoundationPart::Normal;
1150 if (ti->tileh & SLOPE_N) {
1151 z += TILE_HEIGHT;
1153 }
1154 if (IsHalftileSlope(ti->tileh)) {
1155 Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
1156 if ((halftile_corner == Corner::W) || (halftile_corner == Corner::E)) z += TILE_HEIGHT;
1157 if (halftile_corner != Corner::S) {
1158 foundation_part = FoundationPart::Halftile;
1159 if (IsSteepSlope(ti->tileh)) z -= TILE_HEIGHT;
1160 }
1161 }
1162 DrawSelectionSprite(SPR_DOT, PAL_NONE, ti, z, foundation_part);
1163 } else if (_thd.drawstyle & HT_RAIL) {
1164 /* autorail highlight piece under cursor */
1165 HighLightStyle type = _thd.drawstyle & HT_DIR_MASK;
1166 assert(type < HT_DIR_END);
1167 DrawAutorailSelection(ti, _autorail_type[type][0]);
1168 } else if (IsPartOfAutoLine(ti->x, ti->y)) {
1169 /* autorail highlighting long line */
1170 HighLightStyle dir = _thd.drawstyle & HT_DIR_MASK;
1171 uint side;
1172
1173 if (dir == HT_DIR_X || dir == HT_DIR_Y) {
1174 side = 0;
1175 } else {
1176 TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
1177 side = Delta(Delta(TileX(start), TileX(ti->tile)), Delta(TileY(start), TileY(ti->tile)));
1178 }
1179
1180 DrawAutorailSelection(ti, _autorail_type[dir][side]);
1181 }
1182 return;
1183 }
1184
1185 /* Check if it's inside the outer area? */
1186 if (!is_redsq && (tht == TileHighlightType::None || tht == TileHighlightType::Red) && _thd.outersize.x > 0 &&
1187 IsInsideBS(ti->x, _thd.pos.x + _thd.offs.x, _thd.size.x + _thd.outersize.x) &&
1188 IsInsideBS(ti->y, _thd.pos.y + _thd.offs.y, _thd.size.y + _thd.outersize.y)) {
1189 /* Draw a blue rect. */
1191 return;
1192 }
1193}
1194
1201static int GetViewportY(Point tile)
1202{
1203 /* Each increment in X or Y direction moves down by half a tile, i.e. TILE_PIXELS / 2. */
1204 return (tile.y * (int)(TILE_PIXELS / 2) + tile.x * (int)(TILE_PIXELS / 2) - TilePixelHeightOutsideMap(tile.x, tile.y)) << ZOOM_BASE_SHIFT;
1205}
1206
1211{
1212 assert(_vd.dpi.top <= _vd.dpi.top + _vd.dpi.height);
1213 assert(_vd.dpi.left <= _vd.dpi.left + _vd.dpi.width);
1214
1215 Point upper_left = InverseRemapCoords(_vd.dpi.left, _vd.dpi.top);
1216 Point upper_right = InverseRemapCoords(_vd.dpi.left + _vd.dpi.width, _vd.dpi.top);
1217
1218 /* Transformations between tile coordinates and viewport rows/columns: See vp_column_row
1219 * column = y - x
1220 * row = x + y
1221 * x = (row - column) / 2
1222 * y = (row + column) / 2
1223 * Note: (row, columns) pairs are only valid, if they are both even or both odd.
1224 */
1225
1226 /* Columns overlap with neighbouring columns by a half tile.
1227 * - Left column is column of upper_left (rounded down) and one column to the left.
1228 * - Right column is column of upper_right (rounded up) and one column to the right.
1229 * Note: Integer-division does not round down for negative numbers, so ensure rounding with another increment/decrement.
1230 */
1231 int left_column = (upper_left.y - upper_left.x) / (int)TILE_SIZE - 2;
1232 int right_column = (upper_right.y - upper_right.x) / (int)TILE_SIZE + 2;
1233
1234 int potential_bridge_height = ZOOM_BASE * TILE_HEIGHT * _settings_game.construction.max_bridge_height;
1235
1236 /* Rows overlap with neighbouring rows by a half tile.
1237 * The first row that could possibly be visible is the row above upper_left (if it is at height 0).
1238 * Due to integer-division not rounding down for negative numbers, we need another decrement.
1239 */
1240 int row = (upper_left.x + upper_left.y) / (int)TILE_SIZE - 2;
1241 bool last_row = false;
1242 for (; !last_row; row++) {
1243 last_row = true;
1244 for (int column = left_column; column <= right_column; column++) {
1245 /* Valid row/column? */
1246 if ((row + column) % 2 != 0) continue;
1247
1248 Point tilecoord;
1249 tilecoord.x = (row - column) / 2;
1250 tilecoord.y = (row + column) / 2;
1251 assert(column == tilecoord.y - tilecoord.x);
1252 assert(row == tilecoord.y + tilecoord.x);
1253
1254 TileType tile_type;
1255 _cur_ti.x = tilecoord.x * TILE_SIZE;
1256 _cur_ti.y = tilecoord.y * TILE_SIZE;
1257
1258 if (IsInsideBS(tilecoord.x, 0, Map::SizeX()) && IsInsideBS(tilecoord.y, 0, Map::SizeY())) {
1259 /* This includes the south border at Map::MaxX / Map::MaxY. When terraforming we still draw tile selections there. */
1260 _cur_ti.tile = TileXY(tilecoord.x, tilecoord.y);
1261 tile_type = GetTileType(_cur_ti.tile);
1262 } else {
1263 _cur_ti.tile = INVALID_TILE;
1264 tile_type = TileType::Void;
1265 }
1266
1267 if (tile_type != TileType::Void) {
1268 /* We are inside the map => paint landscape. */
1269 std::tie(_cur_ti.tileh, _cur_ti.z) = GetTilePixelSlope(_cur_ti.tile);
1270 } else {
1271 /* We are outside the map => paint black. */
1272 std::tie(_cur_ti.tileh, _cur_ti.z) = GetTilePixelSlopeOutsideMap(tilecoord.x, tilecoord.y);
1273 }
1274
1275 int viewport_y = GetViewportY(tilecoord);
1276
1277 if (viewport_y + MAX_TILE_EXTENT_BOTTOM < _vd.dpi.top) {
1278 /* The tile in this column is not visible yet.
1279 * Tiles in other columns may be visible, but we need more rows in any case. */
1280 last_row = false;
1281 continue;
1282 }
1283
1284 int min_visible_height = viewport_y - (_vd.dpi.top + _vd.dpi.height);
1285 bool tile_visible = min_visible_height <= 0;
1286
1287 if (tile_type != TileType::Void) {
1288 /* Is tile with buildings visible? */
1289 if (min_visible_height < MAX_TILE_EXTENT_TOP) tile_visible = true;
1290
1291 if (IsBridgeAbove(_cur_ti.tile)) {
1292 /* Is the bridge visible? */
1293 TileIndex bridge_tile = GetNorthernBridgeEnd(_cur_ti.tile);
1294 int bridge_height = ZOOM_BASE * (GetBridgePixelHeight(bridge_tile) - TilePixelHeight(_cur_ti.tile));
1295 if (min_visible_height < bridge_height + MAX_TILE_EXTENT_TOP) tile_visible = true;
1296 }
1297
1298 /* Would a higher bridge on a more southern tile be visible?
1299 * If yes, we need to loop over more rows to possibly find one. */
1300 if (min_visible_height < potential_bridge_height + MAX_TILE_EXTENT_TOP) last_row = false;
1301 } else {
1302 /* Outside of map. If we are on the north border of the map, there may still be a bridge visible,
1303 * so we need to loop over more rows to possibly find one. */
1304 if ((tilecoord.x <= 0 || tilecoord.y <= 0) && min_visible_height < potential_bridge_height + MAX_TILE_EXTENT_TOP) last_row = false;
1305 }
1306
1307 if (tile_visible) {
1308 last_row = false;
1309 _vd.foundation_part = FoundationPart::None;
1310 _vd.foundation[FoundationPart::Normal] = -1;
1311 _vd.foundation[FoundationPart::Halftile] = -1;
1312 _vd.last_foundation_child[FoundationPart::Normal] = LAST_CHILD_NONE;
1313 _vd.last_foundation_child[FoundationPart::Halftile] = LAST_CHILD_NONE;
1314
1315 _tile_type_procs[tile_type]->draw_tile_proc(&_cur_ti);
1316 if (_cur_ti.tile != INVALID_TILE) DrawTileSelection(&_cur_ti);
1317 }
1318 }
1319 }
1320}
1321
1330std::string *ViewportAddString(const DrawPixelInfo *dpi, const ViewportSign *sign, ViewportStringFlags flags, Colours colour)
1331{
1332 int left = dpi->left;
1333 int top = dpi->top;
1334 int right = left + dpi->width;
1335 int bottom = top + dpi->height;
1336
1337 bool small = flags.Test(ViewportStringFlag::Small);
1338 int sign_height = ScaleByZoom(WidgetDimensions::scaled.fullbevel.top + GetCharacterHeight(small ? FontSize::Small : FontSize::Normal) + WidgetDimensions::scaled.fullbevel.bottom, dpi->zoom);
1339 int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, dpi->zoom);
1340
1341 if (bottom < sign->top ||
1342 top > sign->top + sign_height ||
1343 right < sign->center - sign_half_width ||
1344 left > sign->center + sign_half_width) {
1345 return nullptr;
1346 }
1347
1348 return &AddStringToDraw(sign->center - sign_half_width, sign->top, colour, flags, small ? sign->width_small : sign->width_normal);
1349}
1350
1351static Rect ExpandRectWithViewportSignMargins(Rect r, ZoomLevel zoom)
1352{
1354 const int max_tw = _viewport_sign_maxwidth / 2 + 1;
1355 const int expand_y = ScaleByZoom(WidgetDimensions::scaled.fullbevel.top + fh + WidgetDimensions::scaled.fullbevel.bottom, zoom);
1356 const int expand_x = ScaleByZoom(WidgetDimensions::scaled.fullbevel.left + max_tw + WidgetDimensions::scaled.fullbevel.right, zoom);
1357
1358 r.left -= expand_x;
1359 r.right += expand_x;
1360 r.top -= expand_y;
1361 r.bottom += expand_y;
1362
1363 return r;
1364}
1365
1372static void ViewportAddTownStrings(DrawPixelInfo *dpi, const std::vector<const Town *> &towns, bool small)
1373{
1374 ViewportStringFlags flags{};
1376
1377 StringID stringid_town = !small && _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_TOWN_NAME;
1378 StringID stringid_town_city = stringid_town;
1379 if (!small) {
1380 stringid_town_city = _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_CITY_POP : STR_VIEWPORT_TOWN_CITY;
1381 }
1382
1383 for (const Town *t : towns) {
1384 std::string *str = ViewportAddString(dpi, &t->cache.sign, flags, Colours::Invalid);
1385 if (str == nullptr) continue;
1386
1387 if (t->larger_town) {
1388 *str = GetString(stringid_town_city, t->index, t->cache.population);
1389 } else {
1390 *str = GetString(stringid_town, t->index, t->cache.population);
1391 }
1392 }
1393}
1394
1401static void ViewportAddSignStrings(DrawPixelInfo *dpi, const std::vector<const Sign *> &signs, bool small)
1402{
1403 ViewportStringFlags flags{};
1404 if (small) flags.Set(ViewportStringFlag::Small);
1405
1406 /* Signs placed by a game script don't have a frame. */
1407 ViewportStringFlags deity_flags{ flags };
1409
1411
1412 for (const Sign *si : signs) {
1413 /* Workaround to make sure white is actually white. The string drawing logic changes all
1414 * colours that are not Colours::Invalid slightly, turning white into a light gray. */
1415 const Colours deity_colour = si->text_colour == Colours::White ? Colours::Invalid : si->text_colour;
1416
1417 std::string *str = ViewportAddString(dpi, &si->sign, (si->owner == OWNER_DEITY) ? deity_flags : flags,
1418 (si->owner == OWNER_NONE) ? Colours::Grey : (si->owner == OWNER_DEITY ? deity_colour : _company_colours[si->owner]));
1419 if (str == nullptr) continue;
1420
1421 *str = GetString(STR_SIGN_NAME, si->index);
1422 }
1423}
1424
1431static void ViewportAddStationStrings(DrawPixelInfo *dpi, const std::vector<const BaseStation *> &stations, bool small)
1432{
1433 /* Transparent station signs have colour text instead of a colour panel. */
1435 if (small) flags.Set(ViewportStringFlag::Small);
1436
1437 for (const BaseStation *st : stations) {
1438 std::string *str = ViewportAddString(dpi, &st->sign, flags, (st->owner == OWNER_NONE || !st->IsInUse()) ? Colours::Grey : _company_colours[st->owner]);
1439 if (str == nullptr) continue;
1440
1441 if (Station::IsExpected(st)) { /* Station */
1442 *str = GetString(small ? STR_STATION_NAME : STR_VIEWPORT_STATION, st->index, st->facilities);
1443 } else { /* Waypoint */
1444 *str = GetString(STR_WAYPOINT_NAME, st->index);
1445 }
1446 }
1447}
1448
1449static void ViewportAddKdtreeSigns(DrawPixelInfo *dpi)
1450{
1451 Rect search_rect{ dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height };
1452 search_rect = ExpandRectWithViewportSignMargins(search_rect, dpi->zoom);
1453
1454 bool show_stations = _display_opt.Test(DisplayOption::ShowStationNames) && _game_mode != GameMode::Menu;
1455 bool show_waypoints = _display_opt.Test(DisplayOption::ShowWaypointNames) && _game_mode != GameMode::Menu;
1456 bool show_towns = _display_opt.Test(DisplayOption::ShowTownNames) && _game_mode != GameMode::Menu;
1458 bool show_competitors = _display_opt.Test(DisplayOption::ShowCompetitorSigns);
1459
1460 /* Collect all the items first and draw afterwards, to ensure layering */
1461 std::vector<const BaseStation *> stations;
1462 std::vector<const Town *> towns;
1463 std::vector<const Sign *> signs;
1464
1465 _viewport_sign_kdtree.FindContained(search_rect.left, search_rect.top, search_rect.right, search_rect.bottom, [&](const ViewportSignKdtreeItem & item) {
1466 switch (item.type) {
1467 case ViewportSignKdtreeItem::VKI_STATION: {
1468 if (!show_stations) break;
1469 const BaseStation *st = BaseStation::Get(std::get<StationID>(item.id));
1470
1471 /* If no facilities are present the station is a ghost station. */
1472 StationFacilities facilities = st->facilities;
1473 if (facilities.None()) facilities = STATION_FACILITY_GHOST;
1474
1475 if (!facilities.Any(_facility_display_opt)) break;
1476
1477 /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
1478 if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
1479
1480 stations.push_back(st);
1481 break;
1482 }
1483
1484 case ViewportSignKdtreeItem::VKI_WAYPOINT: {
1485 if (!show_waypoints) break;
1486 const BaseStation *st = BaseStation::Get(std::get<StationID>(item.id));
1487
1488 /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
1489 if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
1490
1491 stations.push_back(st);
1492 break;
1493 }
1494
1495 case ViewportSignKdtreeItem::VKI_TOWN:
1496 if (!show_towns) break;
1497 towns.push_back(Town::Get(std::get<TownID>(item.id)));
1498 break;
1499
1500 case ViewportSignKdtreeItem::VKI_SIGN: {
1501 if (!show_signs) break;
1502 const Sign *si = Sign::Get(std::get<SignID>(item.id));
1503
1504 /* Don't draw if sign is owned by another company and competitor signs should be hidden.
1505 * Note: It is intentional that also signs owned by OWNER_NONE are hidden. Bankrupt
1506 * companies can leave OWNER_NONE signs after them. */
1507 if (!show_competitors && _local_company != si->owner && si->owner != OWNER_DEITY) break;
1508
1509 signs.push_back(si);
1510 break;
1511 }
1512
1513 default:
1514 NOT_REACHED();
1515 }
1516 });
1517
1518 /* Small versions of signs are used zoom level 4X and higher. */
1519 bool small = dpi->zoom >= ZoomLevel::Out4x;
1520
1521 /* Layering order (bottom to top): Town names, signs, stations */
1522 ViewportAddTownStrings(dpi, towns, small);
1523
1524 /* Do not draw signs nor station names if they are set invisible */
1526
1527 ViewportAddSignStrings(dpi, signs, small);
1528 ViewportAddStationStrings(dpi, stations, small);
1529}
1530
1531
1539void ViewportSign::UpdatePosition(int center, int top, std::string_view str, std::string_view str_small)
1540{
1541 if (this->width_normal != 0) this->MarkDirty();
1542
1543 this->top = top;
1544
1545 this->width_normal = WidgetDimensions::scaled.fullbevel.left + Align(GetStringBoundingBox(str).width, 2) + WidgetDimensions::scaled.fullbevel.right;
1546 this->center = center;
1547
1548 /* zoomed out version */
1549 if (str_small.empty()) str_small = str;
1550 this->width_small = WidgetDimensions::scaled.fullbevel.left + Align(GetStringBoundingBox(str_small, FontSize::Small).width, 2) + WidgetDimensions::scaled.fullbevel.right;
1551
1552 this->MarkDirty();
1553}
1554
1562{
1564
1565 /* We don't know which size will be drawn, so mark the largest area dirty. */
1566 const uint half_width = std::max(this->width_normal, this->width_small) / 2 + 1;
1567 const uint height = WidgetDimensions::scaled.fullbevel.top + std::max(GetCharacterHeight(FontSize::Normal), GetCharacterHeight(FontSize::Small)) + WidgetDimensions::scaled.fullbevel.bottom + 1;
1568
1569 for (ZoomLevel zoom : EnumRange(ZoomLevel::End)) {
1570 zoomlevels[zoom].left = this->center - ScaleByZoom(half_width, zoom);
1571 zoomlevels[zoom].top = this->top - ScaleByZoom(1, zoom);
1572 zoomlevels[zoom].right = this->center + ScaleByZoom(half_width, zoom);
1573 zoomlevels[zoom].bottom = this->top + ScaleByZoom(height, zoom);
1574 }
1575
1576 for (const Window *w : Window::Iterate()) {
1577 if (w->viewport == nullptr) continue;
1578
1579 Viewport &vp = *w->viewport;
1580 if (vp.zoom <= maxzoom) {
1581 assert(vp.width != 0);
1582 Rect &zl = zoomlevels[vp.zoom];
1583 MarkViewportDirty(vp, zl.left, zl.top, zl.right, zl.bottom);
1584 }
1585 }
1586}
1587
1588static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
1589{
1590 for (const TileSpriteToDraw &ts : *tstdv) {
1591 DrawSpriteViewport(ts.image, ts.pal, ts.x, ts.y, ts.sub);
1592 }
1593}
1594
1599static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
1600{
1601 if (psdv->size() < 2) return;
1602
1603 /* We rely on sprites being, for the most part, already ordered.
1604 * So we don't need to move many of them and can keep track of their
1605 * order efficiently by using stack. We always move sprites to the front
1606 * of the current position, i.e. to the top of the stack.
1607 * Also use special constants to indicate sorting state without
1608 * adding extra fields to ParentSpriteToDraw structure.
1609 */
1610 const uint32_t ORDER_COMPARED = UINT32_MAX; // Sprite was compared but we still need to compare the ones preceding it
1611 const uint32_t ORDER_RETURNED = UINT32_MAX - 1; // Mark sorted sprite in case there are other occurrences of it in the stack
1612 std::stack<ParentSpriteToDraw *> sprite_order;
1613 uint32_t next_order = 0;
1614
1615 std::forward_list<std::pair<int64_t, ParentSpriteToDraw *>> sprite_list; // We store sprites in a list sorted by xmin+ymin
1616
1617 /* Initialize sprite list and order. */
1618 for (auto p = psdv->rbegin(); p != psdv->rend(); p++) {
1619 sprite_list.emplace_front((*p)->xmin + (*p)->ymin, *p);
1620 sprite_order.push(*p);
1621 (*p)->order = next_order++;
1622 }
1623
1624 sprite_list.sort();
1625
1626 std::vector<ParentSpriteToDraw *> preceding; // Temporarily stores sprites that precede current and their position in the list
1627 auto preceding_prev = sprite_list.begin(); // Store iterator in case we need to delete a single preceding sprite
1628 auto out = psdv->begin(); // Iterator to output sorted sprites
1629
1630 while (!sprite_order.empty()) {
1631
1632 auto s = sprite_order.top();
1633 sprite_order.pop();
1634
1635 /* Sprite is already sorted, ignore it. */
1636 if (s->order == ORDER_RETURNED) continue;
1637
1638 /* Sprite was already compared, just need to output it. */
1639 if (s->order == ORDER_COMPARED) {
1640 *(out++) = s;
1641 s->order = ORDER_RETURNED;
1642 continue;
1643 }
1644
1645 preceding.clear();
1646
1647 /* We only need sprites with xmin <= s->xmax && ymin <= s->ymax && zmin <= s->zmax
1648 * So by iterating sprites with xmin + ymin <= s->xmax + s->ymax
1649 * we get all we need and some more that we filter out later.
1650 * We don't include zmin into the sum as there are usually more neighbours on x and y than z
1651 * so including it will actually increase the amount of false positives.
1652 * Also min coordinates can be > max so using max(xmin, xmax) + max(ymin, ymax)
1653 * to ensure that we iterate the current sprite as we need to remove it from the list.
1654 */
1655 auto ssum = std::max(s->xmax, s->xmin) + std::max(s->ymax, s->ymin);
1656 auto prev = sprite_list.before_begin();
1657 auto x = sprite_list.begin();
1658 while (x != sprite_list.end() && x->first <= ssum) {
1659 auto p = x->second;
1660 if (p == s) {
1661 /* We found the current sprite, remove it and move on. */
1662 x = sprite_list.erase_after(prev);
1663 continue;
1664 }
1665
1666 auto p_prev = prev;
1667 prev = x++;
1668
1669 if (s->xmax < p->xmin || s->ymax < p->ymin || s->zmax < p->zmin) continue;
1670 if (s->xmin <= p->xmax && // overlap in X?
1671 s->ymin <= p->ymax && // overlap in Y?
1672 s->zmin <= p->zmax) { // overlap in Z?
1673 if (s->xmin + s->xmax + s->ymin + s->ymax + s->zmin + s->zmax <=
1674 p->xmin + p->xmax + p->ymin + p->ymax + p->zmin + p->zmax) {
1675 continue;
1676 }
1677 }
1678 preceding.push_back(p);
1679 preceding_prev = p_prev;
1680 }
1681
1682 if (preceding.empty()) {
1683 /* No preceding sprites, add current one to the output */
1684 *(out++) = s;
1685 s->order = ORDER_RETURNED;
1686 continue;
1687 }
1688
1689 /* Optimization for the case when we only have 1 sprite to move. */
1690 if (preceding.size() == 1) {
1691 auto p = preceding[0];
1692 /* We can only output the preceding sprite if there can't be any other sprites preceding it. */
1693 if (p->xmax <= s->xmax && p->ymax <= s->ymax && p->zmax <= s->zmax) {
1694 p->order = ORDER_RETURNED;
1695 s->order = ORDER_RETURNED;
1696 sprite_list.erase_after(preceding_prev);
1697 *(out++) = p;
1698 *(out++) = s;
1699 continue;
1700 }
1701 }
1702
1703 /* Sort all preceding sprites by order and assign new orders in reverse (as original sorter did). */
1704 std::sort(preceding.begin(), preceding.end(), [](const ParentSpriteToDraw *a, const ParentSpriteToDraw *b) {
1705 return a->order > b->order;
1706 });
1707
1708 s->order = ORDER_COMPARED;
1709 sprite_order.push(s); // Still need to output so push it back for now
1710
1711 for (auto p: preceding) {
1712 p->order = next_order++;
1713 sprite_order.push(p);
1714 }
1715 }
1716}
1717
1718
1719static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
1720{
1721 for (const ParentSpriteToDraw *ps : *psd) {
1722 if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSpriteViewport(ps->image, ps->pal, ps->x, ps->y, ps->sub);
1723
1724 int child_idx = ps->first_child;
1725 while (child_idx >= 0) {
1726 const ChildScreenSpriteToDraw *cs = &(*csstdv)[child_idx];
1727 child_idx = cs->next;
1728 if (cs->relative) {
1729 DrawSpriteViewport(cs->image, cs->pal, ps->left + cs->x, ps->top + cs->y, cs->sub);
1730 } else {
1731 DrawSpriteViewport(cs->image, cs->pal, ps->x + cs->x, ps->y + cs->y, cs->sub);
1732 }
1733 }
1734 }
1735}
1736
1741static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
1742{
1743 for (const ParentSpriteToDraw *ps : *psd) {
1744 Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner
1745 Point pt2 = RemapCoords(ps->xmin , ps->ymax + 1, ps->zmax + 1); // top left corner
1746 Point pt3 = RemapCoords(ps->xmax + 1, ps->ymin , ps->zmax + 1); // top right corner
1747 Point pt4 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmin ); // bottom front corner
1748
1749 DrawBox( pt1.x, pt1.y,
1750 pt2.x - pt1.x, pt2.y - pt1.y,
1751 pt3.x - pt1.x, pt3.y - pt1.y,
1752 pt4.x - pt1.x, pt4.y - pt1.y);
1753 }
1754}
1755
1760{
1762 const DrawPixelInfo *dpi = _cur_dpi;
1763 void *dst;
1764 int right = UnScaleByZoom(dpi->width, dpi->zoom);
1765 int bottom = UnScaleByZoom(dpi->height, dpi->zoom);
1766
1767 PixelColour colour = _string_colourmap[_dirty_block_colour & 0xF];
1768
1769 dst = dpi->dst_ptr;
1770
1771 uint8_t bo = UnScaleByZoom(dpi->left + dpi->top, dpi->zoom) & 1;
1772 do {
1773 for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, colour);
1774 dst = blitter->MoveTo(dst, 0, 1);
1775 } while (--bottom > 0);
1776}
1777
1778static void ViewportDrawStrings(ZoomLevel zoom, const StringSpriteToDrawVector *sstdv)
1779{
1780 for (const StringSpriteToDraw &ss : *sstdv) {
1781 bool small = ss.flags.Test(ViewportStringFlag::Small);
1782 int w = ss.width;
1783 int x = UnScaleByZoom(ss.x, zoom);
1784 int y = UnScaleByZoom(ss.y, zoom);
1785 int h = WidgetDimensions::scaled.fullbevel.top + GetCharacterHeight(small ? FontSize::Small : FontSize::Normal) + WidgetDimensions::scaled.fullbevel.bottom;
1786
1788 if (ss.flags.Test(ViewportStringFlag::ColourRect)) {
1789 if (ss.colour != Colours::Invalid) DrawFrameRect(x, y, x + w - 1, y + h - 1, ss.colour, {});
1790 colour = TextColour::Black;
1791 } else if (ss.flags.Test(ViewportStringFlag::TransparentRect)) {
1792 DrawFrameRect(x, y, x + w - 1, y + h - 1, ss.colour, FrameFlag::Transparent);
1793 }
1794
1795 if (ss.flags.Test(ViewportStringFlag::TextColour)) {
1796 if (ss.colour != Colours::Invalid) colour = ExtendedTextColour{GetColourGradient(ss.colour, Shade::Lighter)};
1797 }
1798
1799 int left = x + WidgetDimensions::scaled.fullbevel.left;
1800 int right = x + w - 1 - WidgetDimensions::scaled.fullbevel.right;
1801 int top = y + WidgetDimensions::scaled.fullbevel.top;
1802
1803 int shadow_offset = 0;
1804 if (small && ss.flags.Test(ViewportStringFlag::Shadow)) {
1805 /* Shadow needs to be shifted 1 pixel. */
1806 shadow_offset = WidgetDimensions::scaled.fullbevel.top;
1807 DrawString(left + shadow_offset, right + shadow_offset, top, ss.string, TextColour::Black, AlignmentH::Centre, false, FontSize::Small);
1808 }
1809
1810 DrawString(left, right, top - shadow_offset, ss.string, colour, AlignmentH::Centre, false, small ? FontSize::Small : FontSize::Normal);
1811 }
1812}
1813
1814void ViewportDoDraw(const Viewport &vp, int left, int top, int right, int bottom)
1815{
1816 _vd.dpi.zoom = vp.zoom;
1817 int mask = ScaleByZoom(-1, vp.zoom);
1818
1819 _vd.combine_sprites = SpriteCombineMode::None;
1820
1821 _vd.dpi.width = (right - left) & mask;
1822 _vd.dpi.height = (bottom - top) & mask;
1823 _vd.dpi.left = left & mask;
1824 _vd.dpi.top = top & mask;
1825 _vd.dpi.pitch = _cur_dpi->pitch;
1826 _vd.last_child = LAST_CHILD_NONE;
1827
1828 int x = UnScaleByZoom(_vd.dpi.left - (vp.virtual_left & mask), vp.zoom) + vp.left;
1829 int y = UnScaleByZoom(_vd.dpi.top - (vp.virtual_top & mask), vp.zoom) + vp.top;
1830
1831 _vd.dpi.dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(_cur_dpi->dst_ptr, x - _cur_dpi->left, y - _cur_dpi->top);
1832 AutoRestoreBackup dpi_backup(_cur_dpi, &_vd.dpi);
1833
1835 ViewportAddVehicles(&_vd.dpi);
1836
1837 ViewportAddKdtreeSigns(&_vd.dpi);
1838
1839 DrawTextEffects(&_vd.dpi);
1840
1841 if (!_vd.tile_sprites_to_draw.empty()) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
1842
1843 for (auto &psd : _vd.parent_sprites_to_draw) {
1844 _vd.parent_sprites_to_sort.push_back(&psd);
1845 }
1846
1847 _vp_sprite_sorter(&_vd.parent_sprites_to_sort);
1848 ViewportDrawParentSprites(&_vd.parent_sprites_to_sort, &_vd.child_screen_sprites_to_draw);
1849
1850 if (_draw_bounding_boxes) ViewportDrawBoundingBoxes(&_vd.parent_sprites_to_sort);
1851 if (_draw_dirty_blocks) ViewportDrawDirtyBlocks();
1852
1853 DrawPixelInfo dp = _vd.dpi;
1854 ZoomLevel zoom = _vd.dpi.zoom;
1855 dp.zoom = ZoomLevel::Min;
1856 dp.width = UnScaleByZoom(dp.width, zoom);
1857 dp.height = UnScaleByZoom(dp.height, zoom);
1858 AutoRestoreBackup cur_dpi(_cur_dpi, &dp);
1859
1860 if (vp.overlay != nullptr && vp.overlay->GetCargoMask().Any() && vp.overlay->GetCompanyMask().Any()) {
1861 /* translate to window coordinates */
1862 dp.left = x;
1863 dp.top = y;
1864 vp.overlay->Draw(&dp);
1865 }
1866
1867 if (!_vd.string_sprites_to_draw.empty()) {
1868 /* translate to world coordinates */
1869 dp.left = UnScaleByZoom(_vd.dpi.left, zoom);
1870 dp.top = UnScaleByZoom(_vd.dpi.top, zoom);
1871 ViewportDrawStrings(zoom, &_vd.string_sprites_to_draw);
1872 }
1873
1874 _vd.string_sprites_to_draw.clear();
1875 _vd.tile_sprites_to_draw.clear();
1876 _vd.parent_sprites_to_draw.clear();
1877 _vd.parent_sprites_to_sort.clear();
1878 _vd.child_screen_sprites_to_draw.clear();
1879}
1880
1881static inline void ViewportDraw(const Viewport &vp, int left, int top, int right, int bottom)
1882{
1883 if (right <= vp.left || bottom <= vp.top) return;
1884
1885 if (left >= vp.left + vp.width) return;
1886
1887 if (left < vp.left) left = vp.left;
1888 if (right > vp.left + vp.width) right = vp.left + vp.width;
1889
1890 if (top >= vp.top + vp.height) return;
1891
1892 if (top < vp.top) top = vp.top;
1893 if (bottom > vp.top + vp.height) bottom = vp.top + vp.height;
1894
1895 ViewportDoDraw(vp,
1896 ScaleByZoom(left - vp.left, vp.zoom) + vp.virtual_left,
1897 ScaleByZoom(top - vp.top, vp.zoom) + vp.virtual_top,
1898 ScaleByZoom(right - vp.left, vp.zoom) + vp.virtual_left,
1899 ScaleByZoom(bottom - vp.top, vp.zoom) + vp.virtual_top
1900 );
1901}
1902
1907{
1909
1910 DrawPixelInfo *dpi = _cur_dpi;
1911
1912 dpi->left += this->left;
1913 dpi->top += this->top;
1914
1915 ViewportDraw(*this->viewport, dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height);
1916
1917 dpi->left -= this->left;
1918 dpi->top -= this->top;
1919}
1920
1931static inline void ClampViewportToMap(const Viewport &vp, int *scroll_x, int *scroll_y)
1932{
1933 /* Centre of the viewport is hot spot. */
1934 Point pt = {
1935 *scroll_x + vp.virtual_width / 2,
1936 *scroll_y + vp.virtual_height / 2
1937 };
1938
1939 /* Find nearest tile that is within borders of the map. */
1940 bool clamped;
1941 pt = InverseRemapCoords2(pt.x, pt.y, true, &clamped);
1942
1943 if (clamped) {
1944 /* Convert back to viewport coordinates and remove centering. */
1945 pt = RemapCoords2(pt.x, pt.y);
1946 *scroll_x = pt.x - vp.virtual_width / 2;
1947 *scroll_y = pt.y - vp.virtual_height / 2;
1948 }
1949}
1950
1963static void ClampSmoothScroll(uint32_t delta_ms, int64_t delta_hi, int64_t delta_lo, int &delta_hi_clamped, int &delta_lo_clamped)
1964{
1966 constexpr int PIXELS_PER_TILE = TILE_PIXELS * 2 * ZOOM_BASE;
1967
1968 assert(delta_hi != 0);
1969
1970 /* Move at most 75% of the distance every 30ms, for a smooth experience */
1971 int64_t delta_left = delta_hi * std::pow(0.75, delta_ms / 30.0);
1972 /* Move never more than 16 tiles per 30ms. */
1973 int max_scroll = Map::ScaleBySize1D(16 * PIXELS_PER_TILE * delta_ms / 30);
1974
1975 /* We never go over the max_scroll speed. */
1976 delta_hi_clamped = Clamp(delta_hi - delta_left, -max_scroll, max_scroll);
1977 /* The lower delta is in ratio of the higher delta, so we keep going straight at the destination. */
1978 delta_lo_clamped = delta_lo * delta_hi_clamped / delta_hi;
1979
1980 /* Ensure we always move (delta_hi can't be zero). */
1981 if (delta_hi_clamped == 0) {
1982 delta_hi_clamped = delta_hi > 0 ? 1 : -1;
1983 }
1984}
1985
1991void UpdateViewportPosition(Window *w, uint32_t delta_ms)
1992{
1993 ViewportData &vp = *w->viewport;
1994
1995 if (vp.follow_vehicle != VehicleID::Invalid()) {
1996 const Vehicle *veh = Vehicle::Get(vp.follow_vehicle)->GetMovingFront();
1997 Point pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
1998
1999 vp.scrollpos_x = pt.x;
2000 vp.scrollpos_y = pt.y;
2001 SetViewportPosition(w, pt.x, pt.y);
2002 } else {
2003 /* Ensure the destination location is within the map */
2005
2006 int delta_x = vp.dest_scrollpos_x - vp.scrollpos_x;
2007 int delta_y = vp.dest_scrollpos_y - vp.scrollpos_y;
2008
2009 int current_x = vp.scrollpos_x;
2010 int current_y = vp.scrollpos_y;
2011
2012 bool update_overlay = false;
2013 if (delta_x != 0 || delta_y != 0) {
2014 if (_settings_client.gui.smooth_scroll) {
2015 int delta_x_clamped;
2016 int delta_y_clamped;
2017
2018 if (abs(delta_x) > abs(delta_y)) {
2019 ClampSmoothScroll(delta_ms, delta_x, delta_y, delta_x_clamped, delta_y_clamped);
2020 } else {
2021 ClampSmoothScroll(delta_ms, delta_y, delta_x, delta_y_clamped, delta_x_clamped);
2022 }
2023
2024 vp.scrollpos_x += delta_x_clamped;
2025 vp.scrollpos_y += delta_y_clamped;
2026 } else {
2029 }
2030 update_overlay = (vp.scrollpos_x == vp.dest_scrollpos_x &&
2031 vp.scrollpos_y == vp.dest_scrollpos_y);
2032 }
2033
2035
2036 /* When moving small amounts around the border we can get stuck, and
2037 * not actually move. In those cases, teleport to the destination. */
2038 if ((delta_x != 0 || delta_y != 0) && current_x == vp.scrollpos_x && current_y == vp.scrollpos_y) {
2041 }
2042
2043 SetViewportPosition(w, vp.scrollpos_x, vp.scrollpos_y);
2044 if (update_overlay) RebuildViewportOverlay(w);
2045 }
2046}
2047
2058static bool MarkViewportDirty(const Viewport &vp, int left, int top, int right, int bottom)
2059{
2060 /* Rounding wrt. zoom-out level */
2061 right += (1 << to_underlying(vp.zoom)) - 1;
2062 bottom += (1 << to_underlying(vp.zoom)) - 1;
2063
2064 right -= vp.virtual_left;
2065 if (right <= 0) return false;
2066
2067 bottom -= vp.virtual_top;
2068 if (bottom <= 0) return false;
2069
2070 left = std::max(0, left - vp.virtual_left);
2071
2072 if (left >= vp.virtual_width) return false;
2073
2074 top = std::max(0, top - vp.virtual_top);
2075
2076 if (top >= vp.virtual_height) return false;
2077
2079 UnScaleByZoomLower(left, vp.zoom) + vp.left,
2080 UnScaleByZoomLower(top, vp.zoom) + vp.top,
2081 UnScaleByZoom(right, vp.zoom) + vp.left + 1,
2082 UnScaleByZoom(bottom, vp.zoom) + vp.top + 1
2083 );
2084
2085 return true;
2086}
2087
2097bool MarkAllViewportsDirty(int left, int top, int right, int bottom)
2098{
2099 bool dirty = false;
2100
2101 for (const Window *w : Window::Iterate()) {
2102 if (w->viewport != nullptr) {
2103 assert(w->viewport->width != 0);
2104 if (MarkViewportDirty(*w->viewport, left, top, right, bottom)) dirty = true;
2105 }
2106 }
2107
2108 return dirty;
2109}
2110
2111void ConstrainAllViewportsZoom()
2112{
2113 for (Window *w : Window::Iterate()) {
2114 if (w->viewport == nullptr) continue;
2115
2116 ZoomLevel zoom = Clamp(w->viewport->zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max);
2117 if (zoom != w->viewport->zoom) {
2118 while (w->viewport->zoom < zoom) DoZoomInOutWindow(ZOOM_OUT, w);
2119 while (w->viewport->zoom > zoom) DoZoomInOutWindow(ZOOM_IN, w);
2120 }
2121 }
2122}
2123
2131void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
2132{
2133 Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, tile_height_override * TILE_HEIGHT);
2136 pt.y - MAX_TILE_EXTENT_TOP - ZOOM_BASE * TILE_HEIGHT * bridge_level_offset,
2139}
2140
2149{
2150 int x_size = _thd.size.x;
2151 int y_size = _thd.size.y;
2152
2153 if (!_thd.diagonal) { // Selecting in a straight rectangle (or a single square)
2154 int x_start = _thd.pos.x;
2155 int y_start = _thd.pos.y;
2156
2157 if (_thd.outersize.x != 0) {
2158 x_size += _thd.outersize.x;
2159 x_start += _thd.offs.x;
2160 y_size += _thd.outersize.y;
2161 y_start += _thd.offs.y;
2162 }
2163
2164 x_size -= TILE_SIZE;
2165 y_size -= TILE_SIZE;
2166
2167 assert(x_size >= 0);
2168 assert(y_size >= 0);
2169
2170 int x_end = Clamp(x_start + x_size, 0, Map::SizeX() * TILE_SIZE - TILE_SIZE);
2171 int y_end = Clamp(y_start + y_size, 0, Map::SizeY() * TILE_SIZE - TILE_SIZE);
2172
2173 x_start = Clamp(x_start, 0, Map::SizeX() * TILE_SIZE - TILE_SIZE);
2174 y_start = Clamp(y_start, 0, Map::SizeY() * TILE_SIZE - TILE_SIZE);
2175
2176 /* make sure everything is multiple of TILE_SIZE */
2177 assert((x_end | y_end | x_start | y_start) % TILE_SIZE == 0);
2178
2179 /* How it works:
2180 * Suppose we have to mark dirty rectangle of 3x4 tiles:
2181 * x
2182 * xxx
2183 * xxxxx
2184 * xxxxx
2185 * xxx
2186 * x
2187 * This algorithm marks dirty columns of tiles, so it is done in 3+4-1 steps:
2188 * 1) x 2) x
2189 * xxx Oxx
2190 * Oxxxx xOxxx
2191 * xxxxx Oxxxx
2192 * xxx xxx
2193 * x x
2194 * And so forth...
2195 */
2196
2197 int top_x = x_end; // coordinates of top dirty tile
2198 int top_y = y_start;
2199 int bot_x = top_x; // coordinates of bottom dirty tile
2200 int bot_y = top_y;
2201
2202 do {
2203 /* topmost dirty point */
2204 TileIndex top_tile = TileVirtXY(top_x, top_y);
2205 Point top = RemapCoords(top_x, top_y, GetTileMaxPixelZ(top_tile));
2206
2207 /* bottommost point */
2208 TileIndex bottom_tile = TileVirtXY(bot_x, bot_y);
2209 Point bot = RemapCoords(bot_x + TILE_SIZE, bot_y + TILE_SIZE, GetTilePixelZ(bottom_tile)); // bottommost point
2210
2211 /* the 'x' coordinate of 'top' and 'bot' is the same (and always in the same distance from tile middle),
2212 * tile height/slope affects only the 'y' on-screen coordinate! */
2213
2214 int l = top.x - TILE_PIXELS * ZOOM_BASE; // 'x' coordinate of left side of the dirty rectangle
2215 int t = top.y; // 'y' coordinate of top side of the dirty rectangle
2216 int r = top.x + TILE_PIXELS * ZOOM_BASE; // 'x' coordinate of right side of the dirty rectangle
2217 int b = bot.y; // 'y' coordinate of bottom side of the dirty rectangle
2218
2219 static const int OVERLAY_WIDTH = 4 * ZOOM_BASE; // part of selection sprites is drawn outside the selected area (in particular: terraforming)
2220
2221 /* For halftile foundations on SLOPE_STEEP_S the sprite extents some more towards the top */
2222 MarkAllViewportsDirty(l - OVERLAY_WIDTH, t - OVERLAY_WIDTH - TILE_HEIGHT * ZOOM_BASE, r + OVERLAY_WIDTH, b + OVERLAY_WIDTH);
2223
2224 /* haven't we reached the topmost tile yet? */
2225 if (top_x != x_start) {
2226 top_x -= TILE_SIZE;
2227 } else {
2228 top_y += TILE_SIZE;
2229 }
2230
2231 /* the way the bottom tile changes is different when we reach the bottommost tile */
2232 if (bot_y != y_end) {
2233 bot_y += TILE_SIZE;
2234 } else {
2235 bot_x -= TILE_SIZE;
2236 }
2237 } while (bot_x >= top_x);
2238 } else { // Selecting in a 45 degrees rotated (diagonal) rectangle.
2239 /* a_size, b_size describe a rectangle with rotated coordinates */
2240 int a_size = x_size + y_size, b_size = x_size - y_size;
2241
2242 int interval_a = a_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
2243 int interval_b = b_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
2244
2245 for (int a = -interval_a; a != a_size + interval_a; a += interval_a) {
2246 for (int b = -interval_b; b != b_size + interval_b; b += interval_b) {
2247 uint x = (_thd.pos.x + (a + b) / 2) / TILE_SIZE;
2248 uint y = (_thd.pos.y + (a - b) / 2) / TILE_SIZE;
2249
2250 if (x < Map::MaxX() && y < Map::MaxY()) {
2252 }
2253 }
2254 }
2255 }
2256}
2257
2258
2259void SetSelectionRed(bool b)
2260{
2261 _thd.make_square_red = b;
2263}
2264
2273static bool CheckClickOnViewportSign(const Viewport &vp, int x, int y, const ViewportSign *sign)
2274{
2275 bool small = (vp.zoom >= ZoomLevel::Out4x);
2276 int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, vp.zoom);
2277 int sign_height = ScaleByZoom(WidgetDimensions::scaled.fullbevel.top + GetCharacterHeight(small ? FontSize::Small : FontSize::Normal) + WidgetDimensions::scaled.fullbevel.bottom, vp.zoom);
2278
2279 return y >= sign->top && y < sign->top + sign_height &&
2280 x >= sign->center - sign_half_width && x < sign->center + sign_half_width;
2281}
2282
2283
2291static bool CheckClickOnViewportSign(const Viewport &vp, int x, int y)
2292{
2293 if (_game_mode == GameMode::Menu) return false;
2294
2295 x = ScaleByZoom(x - vp.left, vp.zoom) + vp.virtual_left;
2296 y = ScaleByZoom(y - vp.top, vp.zoom) + vp.virtual_top;
2297
2298 Rect search_rect{ x - 1, y - 1, x + 1, y + 1 };
2299 search_rect = ExpandRectWithViewportSignMargins(search_rect, vp.zoom);
2300
2303 bool show_towns = _display_opt.Test(DisplayOption::ShowTownNames);
2305 bool show_competitors = _display_opt.Test(DisplayOption::ShowCompetitorSigns);
2306
2307 /* Topmost of each type that was hit */
2308 BaseStation *st = nullptr, *last_st = nullptr;
2309 Town *t = nullptr, *last_t = nullptr;
2310 Sign *si = nullptr, *last_si = nullptr;
2311
2312 /* See ViewportAddKdtreeSigns() for details on the search logic */
2313 _viewport_sign_kdtree.FindContained(search_rect.left, search_rect.top, search_rect.right, search_rect.bottom, [&](const ViewportSignKdtreeItem & item) {
2314 switch (item.type) {
2315 case ViewportSignKdtreeItem::VKI_STATION: {
2316 if (!show_stations) break;
2317 st = BaseStation::Get(std::get<StationID>(item.id));
2318 if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
2319
2320 StationFacilities facilities = st->facilities;
2321 if (facilities.None()) facilities = STATION_FACILITY_GHOST;
2322 if (!facilities.Any(_facility_display_opt)) break;
2323
2324 if (CheckClickOnViewportSign(vp, x, y, &st->sign)) last_st = st;
2325 break;
2326 }
2327
2328 case ViewportSignKdtreeItem::VKI_WAYPOINT:
2329 if (!show_waypoints) break;
2330 st = BaseStation::Get(std::get<StationID>(item.id));
2331 if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
2332 if (CheckClickOnViewportSign(vp, x, y, &st->sign)) last_st = st;
2333 break;
2334
2335 case ViewportSignKdtreeItem::VKI_TOWN:
2336 if (!show_towns) break;
2337 t = Town::Get(std::get<TownID>(item.id));
2338 if (CheckClickOnViewportSign(vp, x, y, &t->cache.sign)) last_t = t;
2339 break;
2340
2341 case ViewportSignKdtreeItem::VKI_SIGN:
2342 if (!show_signs) break;
2343 si = Sign::Get(std::get<SignID>(item.id));
2344 if (!show_competitors && _local_company != si->owner && si->owner != OWNER_DEITY) break;
2345 if (CheckClickOnViewportSign(vp, x, y, &si->sign)) last_si = si;
2346 break;
2347
2348 default:
2349 NOT_REACHED();
2350 }
2351 });
2352
2353 /* Select which hit to handle based on priority */
2354 if (last_st != nullptr) {
2355 if (Station::IsExpected(last_st)) {
2356 ShowStationViewWindow(last_st->index);
2357 } else {
2359 }
2360 return true;
2361 } else if (last_t != nullptr) {
2362 ShowTownViewWindow(last_t->index);
2363 return true;
2364 } else if (last_si != nullptr) {
2365 HandleClickOnSign(last_si);
2366 return true;
2367 } else {
2368 return false;
2369 }
2370}
2371
2372
2373ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeStation(StationID id)
2374{
2375 ViewportSignKdtreeItem item;
2376 item.type = VKI_STATION;
2377 item.id = id;
2378
2379 const Station *st = Station::Get(id);
2380 assert(st->sign.kdtree_valid);
2381 item.center = st->sign.center;
2382 item.top = st->sign.top;
2383
2384 /* Assume the sign can be a candidate for drawing, so measure its width */
2385 _viewport_sign_maxwidth = std::max<int>({_viewport_sign_maxwidth, st->sign.width_normal, st->sign.width_small});
2386
2387 return item;
2388}
2389
2390ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeWaypoint(StationID id)
2391{
2392 ViewportSignKdtreeItem item;
2393 item.type = VKI_WAYPOINT;
2394 item.id = id;
2395
2396 const Waypoint *st = Waypoint::Get(id);
2397 assert(st->sign.kdtree_valid);
2398 item.center = st->sign.center;
2399 item.top = st->sign.top;
2400
2401 /* Assume the sign can be a candidate for drawing, so measure its width */
2402 _viewport_sign_maxwidth = std::max<int>({_viewport_sign_maxwidth, st->sign.width_normal, st->sign.width_small});
2403
2404 return item;
2405}
2406
2407ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeTown(TownID id)
2408{
2409 ViewportSignKdtreeItem item;
2410 item.type = VKI_TOWN;
2411 item.id = id;
2412
2413 const Town *town = Town::Get(id);
2414 assert(town->cache.sign.kdtree_valid);
2415 item.center = town->cache.sign.center;
2416 item.top = town->cache.sign.top;
2417
2418 /* Assume the sign can be a candidate for drawing, so measure its width */
2419 _viewport_sign_maxwidth = std::max<int>({_viewport_sign_maxwidth, town->cache.sign.width_normal, town->cache.sign.width_small});
2420
2421 return item;
2422}
2423
2424ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeSign(SignID id)
2425{
2426 ViewportSignKdtreeItem item;
2427 item.type = VKI_SIGN;
2428 item.id = id;
2429
2430 const Sign *sign = Sign::Get(id);
2431 assert(sign->sign.kdtree_valid);
2432 item.center = sign->sign.center;
2433 item.top = sign->sign.top;
2434
2435 /* Assume the sign can be a candidate for drawing, so measure its width */
2436 _viewport_sign_maxwidth = std::max<int>({_viewport_sign_maxwidth, sign->sign.width_normal, sign->sign.width_small});
2437
2438 return item;
2439}
2440
2441void RebuildViewportKdtree()
2442{
2443 /* Reset biggest size sign seen */
2444 _viewport_sign_maxwidth = 0;
2445
2446 std::vector<ViewportSignKdtreeItem> items;
2448
2449 for (const Station *st : Station::Iterate()) {
2450 if (st->sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeStation(st->index));
2451 }
2452
2453 for (const Waypoint *wp : Waypoint::Iterate()) {
2454 if (wp->sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeWaypoint(wp->index));
2455 }
2456
2457 for (const Town *town : Town::Iterate()) {
2458 if (town->cache.sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeTown(town->index));
2459 }
2460
2461 for (const Sign *sign : Sign::Iterate()) {
2462 if (sign->sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeSign(sign->index));
2463 }
2464
2465 _viewport_sign_kdtree.Build(items.begin(), items.end());
2466}
2467
2468
2469static bool CheckClickOnLandscape(const Viewport &vp, int x, int y)
2470{
2471 Point pt = TranslateXYToTileCoord(vp, x, y);
2472
2473 if (pt.x != -1) return ClickTile(TileVirtXY(pt.x, pt.y));
2474 return true;
2475}
2476
2477static void PlaceObject()
2478{
2479 Point pt;
2480 Window *w;
2481
2482 pt = GetTileBelowCursor();
2483 if (pt.x == -1) return;
2484
2485 if ((_thd.place_mode & HT_DRAG_MASK) == HT_POINT) {
2486 pt.x += TILE_SIZE / 2;
2487 pt.y += TILE_SIZE / 2;
2488 }
2489
2490 _tile_fract_coords.x = pt.x & TILE_UNIT_MASK;
2491 _tile_fract_coords.y = pt.y & TILE_UNIT_MASK;
2492
2493 w = _thd.GetCallbackWnd();
2494 if (w != nullptr) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
2495}
2496
2497
2498bool HandleViewportClicked(const Viewport &vp, int x, int y)
2499{
2500 const Vehicle *v = CheckClickOnVehicle(vp, x, y);
2501
2502 if (_thd.place_mode & HT_VEHICLE) {
2503 if (v != nullptr && VehicleClicked(v)) return true;
2504 }
2505
2506 /* Vehicle placement mode already handled above. */
2507 if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
2508 PlaceObject();
2509 return true;
2510 }
2511
2512 if (CheckClickOnViewportSign(vp, x, y)) return true;
2513 bool result = CheckClickOnLandscape(vp, x, y);
2514
2515 if (v != nullptr) {
2516 Debug(Facility::Misc, Severity::Warning, "Vehicle {} (index {}) at {}", v->unitnumber, v->index, fmt::ptr(v));
2518 v = v->First();
2519 if (IsCtrlPressed() && v->owner == _local_company) {
2520 StartStopVehicle(v, true);
2521 } else {
2523 }
2524 }
2525 return true;
2526 }
2527 return result;
2528}
2529
2530void RebuildViewportOverlay(Window *w)
2531{
2532 if (w->viewport->overlay != nullptr &&
2533 w->viewport->overlay->GetCompanyMask().Any() &&
2534 w->viewport->overlay->GetCargoMask().Any()) {
2535 w->viewport->overlay->SetDirty();
2536 w->SetDirty();
2537 }
2538}
2539
2549bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
2550{
2551 /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
2552 if (z == -1) {
2553 if ( x >= 0 && x <= (int)Map::SizeX() * (int)TILE_SIZE - 1
2554 && y >= 0 && y <= (int)Map::SizeY() * (int)TILE_SIZE - 1) {
2555 z = GetSlopePixelZ(x, y);
2556 } else {
2557 z = TileHeightOutsideMap(x / (int)TILE_SIZE, y / (int)TILE_SIZE);
2558 }
2559 }
2560
2561 Point pt = MapXYZToViewport(*w->viewport, x, y, z);
2562 w->viewport->CancelFollow(*w);
2563
2564 if (w->viewport->dest_scrollpos_x == pt.x && w->viewport->dest_scrollpos_y == pt.y) return false;
2565
2566 if (instant) {
2567 w->viewport->scrollpos_x = pt.x;
2568 w->viewport->scrollpos_y = pt.y;
2569 RebuildViewportOverlay(w);
2570 }
2571
2572 w->viewport->dest_scrollpos_x = pt.x;
2573 w->viewport->dest_scrollpos_y = pt.y;
2574 return true;
2575}
2576
2584bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
2585{
2586 return ScrollWindowTo(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, -1, w, instant);
2587}
2588
2595bool ScrollMainWindowToTile(TileIndex tile, bool instant)
2596{
2597 return ScrollMainWindowTo(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, -1, instant);
2598}
2599
2605{
2606 TileIndex old;
2607
2608 old = _thd.redsq;
2609 _thd.redsq = tile;
2610
2611 if (tile != old) {
2612 if (tile != INVALID_TILE) MarkTileDirtyByTile(tile);
2613 if (old != INVALID_TILE) MarkTileDirtyByTile(old);
2614 }
2615}
2616
2622void SetTileSelectSize(int w, int h)
2623{
2624 _thd.new_size.x = w * TILE_SIZE;
2625 _thd.new_size.y = h * TILE_SIZE;
2626 _thd.new_outersize.x = 0;
2627 _thd.new_outersize.y = 0;
2628}
2629
2630void SetTileSelectBigSize(int ox, int oy, int sx, int sy)
2631{
2632 _thd.offs.x = ox * TILE_SIZE;
2633 _thd.offs.y = oy * TILE_SIZE;
2634 _thd.new_outersize.x = sx * TILE_SIZE;
2635 _thd.new_outersize.y = sy * TILE_SIZE;
2636}
2637
2644static HighLightStyle GetAutorailHT(int x, int y)
2645{
2647}
2648
2653{
2654 this->pos.x = 0;
2655 this->pos.y = 0;
2656 this->new_pos.x = 0;
2657 this->new_pos.y = 0;
2658}
2659
2665{
2666 return (this->place_mode & HT_DIAGONAL) != 0 && IsCtrlPressed() && IsLeftButtonDown();
2667}
2668
2677
2678
2679
2688{
2689 int x1;
2690 int y1;
2691
2692 if (_thd.freeze) return;
2693
2694 HighLightStyle new_drawstyle = HT_NONE;
2695 bool new_diagonal = false;
2696
2697 if ((_thd.place_mode & HT_DRAG_MASK) == HT_SPECIAL) {
2698 x1 = _thd.selend.x;
2699 y1 = _thd.selend.y;
2700 if (x1 != -1) {
2701 int x2 = _thd.selstart.x & ~TILE_UNIT_MASK;
2702 int y2 = _thd.selstart.y & ~TILE_UNIT_MASK;
2703 x1 &= ~TILE_UNIT_MASK;
2704 y1 &= ~TILE_UNIT_MASK;
2705
2706 if (_thd.IsDraggingDiagonal()) {
2707 new_diagonal = true;
2708 } else {
2709 if (x1 >= x2) std::swap(x1, x2);
2710 if (y1 >= y2) std::swap(y1, y2);
2711 }
2712 _thd.new_pos.x = x1;
2713 _thd.new_pos.y = y1;
2714 _thd.new_size.x = x2 - x1;
2715 _thd.new_size.y = y2 - y1;
2716 if (!new_diagonal) {
2717 _thd.new_size.x += TILE_SIZE;
2718 _thd.new_size.y += TILE_SIZE;
2719 }
2720 new_drawstyle = _thd.next_drawstyle;
2721 }
2722 } else if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
2723 Point pt = GetTileBelowCursor();
2724 x1 = pt.x;
2725 y1 = pt.y;
2726 if (x1 != -1) {
2727 switch (_thd.place_mode & HT_DRAG_MASK) {
2728 case HT_RECT:
2729 new_drawstyle = HT_RECT;
2730 break;
2731 case HT_POINT:
2732 new_drawstyle = HT_POINT;
2733 x1 += TILE_SIZE / 2;
2734 y1 += TILE_SIZE / 2;
2735 break;
2736 case HT_RAIL:
2737 /* Draw one highlighted tile in any direction */
2738 new_drawstyle = GetAutorailHT(pt.x, pt.y);
2739 break;
2740 case HT_LINE:
2741 switch (_thd.place_mode & HT_DIR_MASK) {
2742 case HT_DIR_X: new_drawstyle = HT_LINE | HT_DIR_X; break;
2743 case HT_DIR_Y: new_drawstyle = HT_LINE | HT_DIR_Y; break;
2744
2745 case HT_DIR_HU:
2746 case HT_DIR_HL:
2747 new_drawstyle = (pt.x & TILE_UNIT_MASK) + (pt.y & TILE_UNIT_MASK) <= TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
2748 break;
2749
2750 case HT_DIR_VL:
2751 case HT_DIR_VR:
2752 new_drawstyle = (pt.x & TILE_UNIT_MASK) > (pt.y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2753 break;
2754
2755 default: NOT_REACHED();
2756 }
2757 _thd.selstart.x = x1 & ~TILE_UNIT_MASK;
2758 _thd.selstart.y = y1 & ~TILE_UNIT_MASK;
2759 break;
2760 default:
2761 NOT_REACHED();
2762 }
2763 _thd.new_pos.x = x1 & ~TILE_UNIT_MASK;
2764 _thd.new_pos.y = y1 & ~TILE_UNIT_MASK;
2765 }
2766 }
2767
2768 /* redraw selection */
2769 if (_thd.drawstyle != new_drawstyle ||
2770 _thd.pos.x != _thd.new_pos.x || _thd.pos.y != _thd.new_pos.y ||
2771 _thd.size.x != _thd.new_size.x || _thd.size.y != _thd.new_size.y ||
2772 _thd.outersize.x != _thd.new_outersize.x ||
2773 _thd.outersize.y != _thd.new_outersize.y ||
2774 _thd.diagonal != new_diagonal) {
2775 /* Clear the old tile selection? */
2776 if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
2777
2778 _thd.drawstyle = new_drawstyle;
2779 _thd.pos = _thd.new_pos;
2780 _thd.size = _thd.new_size;
2781 _thd.outersize = _thd.new_outersize;
2782 _thd.diagonal = new_diagonal;
2783 _thd.dirty = 0xff;
2784
2785 /* Draw the new tile selection? */
2786 if ((new_drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
2787 }
2788}
2789
2794static inline void ShowMeasurementTooltips(EncodedString &&text)
2795{
2796 if (!_settings_client.gui.measure_tooltip) return;
2797 GuiShowTooltips(_thd.GetCallbackWnd(), std::move(text), TooltipCloseCondition::ExitViewport);
2798}
2799
2800static void HideMeasurementTooltips()
2801{
2802 CloseWindowById(WindowClass::ToolTips, 0);
2803}
2804
2812{
2813 _thd.select_method = method;
2814 _thd.select_proc = process;
2815 _thd.selend.x = TileX(tile) * TILE_SIZE;
2816 _thd.selstart.x = TileX(tile) * TILE_SIZE;
2817 _thd.selend.y = TileY(tile) * TILE_SIZE;
2818 _thd.selstart.y = TileY(tile) * TILE_SIZE;
2819
2820 /* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
2821 * In effect, placement starts from the centre of a tile
2822 */
2823 if (method == VPM_X_OR_Y || method == VPM_FIX_X || method == VPM_FIX_Y) {
2824 _thd.selend.x += TILE_SIZE / 2;
2825 _thd.selend.y += TILE_SIZE / 2;
2826 _thd.selstart.x += TILE_SIZE / 2;
2827 _thd.selstart.y += TILE_SIZE / 2;
2828 }
2829
2830 HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
2831 if ((_thd.place_mode & HT_DRAG_MASK) == HT_RECT) {
2832 _thd.place_mode = HT_SPECIAL | others;
2833 _thd.next_drawstyle = HT_RECT | others;
2834 } else if (_thd.place_mode & (HT_RAIL | HT_LINE)) {
2835 _thd.place_mode = HT_SPECIAL | others;
2836 _thd.next_drawstyle = _thd.drawstyle | others;
2837 } else {
2838 _thd.place_mode = HT_SPECIAL | others;
2839 _thd.next_drawstyle = HT_POINT | others;
2840 }
2842}
2843
2849{
2850 _thd.select_method = VPM_X_AND_Y;
2851 _thd.select_proc = process;
2852 _thd.selstart.x = 0;
2853 _thd.selstart.y = 0;
2854 _thd.next_drawstyle = HT_RECT;
2855
2857}
2858
2859void VpSetPlaceSizingLimit(int limit)
2860{
2861 _thd.sizelimit = limit;
2862}
2863
2870{
2871 uint64_t distance = DistanceManhattan(from, to) + 1;
2872
2873 _thd.selend.x = TileX(to) * TILE_SIZE;
2874 _thd.selend.y = TileY(to) * TILE_SIZE;
2875 _thd.selstart.x = TileX(from) * TILE_SIZE;
2876 _thd.selstart.y = TileY(from) * TILE_SIZE;
2877 _thd.next_drawstyle = HT_RECT;
2878
2879 /* show measurement only if there is any length to speak of */
2880 if (distance > 1) {
2881 ShowMeasurementTooltips(GetEncodedString(STR_MEASURE_LENGTH, distance));
2882 } else {
2883 HideMeasurementTooltips();
2884 }
2885}
2886
2887static void VpStartPreSizing()
2888{
2889 _thd.selend.x = -1;
2891}
2892
2901{
2902 int fxpy = _tile_fract_coords.x + _tile_fract_coords.y;
2903 int sxpy = (_thd.selend.x & TILE_UNIT_MASK) + (_thd.selend.y & TILE_UNIT_MASK);
2904 int fxmy = _tile_fract_coords.x - _tile_fract_coords.y;
2905 int sxmy = (_thd.selend.x & TILE_UNIT_MASK) - (_thd.selend.y & TILE_UNIT_MASK);
2906
2907 switch (direction) {
2908 default: NOT_REACHED();
2909 case DiagDirection::SE: // end piece is lower right
2910 if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
2911 if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
2912 return HT_DIR_Y;
2913
2914 case DiagDirection::NW:
2915 if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
2916 if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
2917 return HT_DIR_Y;
2918
2919 case DiagDirection::SW:
2920 if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
2921 if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
2922 return HT_DIR_X;
2923
2924 case DiagDirection::NE:
2925 if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
2926 if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
2927 return HT_DIR_X;
2928 }
2929}
2930
2944static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
2945{
2946 uint start_x = TileX(start_tile);
2947 uint start_y = TileY(start_tile);
2948 uint end_x = TileX(end_tile);
2949 uint end_y = TileY(end_tile);
2950
2951 switch (style & HT_DRAG_MASK) {
2952 case HT_RAIL:
2953 case HT_LINE: return (end_x > start_x || (end_x == start_x && end_y > start_y));
2954
2955 case HT_RECT:
2956 case HT_POINT: return (end_x != start_x && end_y < start_y);
2957 default: NOT_REACHED();
2958 }
2959
2960 return false;
2961}
2962
2978static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
2979{
2980 bool swap = SwapDirection(style, start_tile, end_tile);
2981 uint h0, h1; // Start height and end height.
2982
2983 if (start_tile == end_tile) return 0;
2984 if (swap) std::swap(start_tile, end_tile);
2985
2986 switch (style & HT_DRAG_MASK) {
2987 case HT_RECT:
2988 /* In the case of an area we can determine whether we were dragging south or
2989 * east by checking the X-coordinates of the tiles */
2990 if (TileX(end_tile) > TileX(start_tile)) {
2991 /* Dragging south does not need to change the start tile. */
2992 end_tile = TileAddByDir(end_tile, Direction::S);
2993 } else {
2994 /* Dragging east. */
2995 start_tile = TileAddByDir(start_tile, Direction::SW);
2996 end_tile = TileAddByDir(end_tile, Direction::SE);
2997 }
2998 [[fallthrough]];
2999
3000 case HT_POINT:
3001 h0 = TileHeight(start_tile);
3002 h1 = TileHeight(end_tile);
3003 break;
3004 default: { // All other types, this is mostly only line/autorail
3005 static const HighLightStyle flip_style_direction[] = {
3007 };
3008 static const std::pair<TileIndexDiffC, TileIndexDiffC> start_heightdiff_line_by_dir[] = {
3009 { {1, 0}, {1, 1} }, // HT_DIR_X
3010 { {0, 1}, {1, 1} }, // HT_DIR_Y
3011 { {1, 0}, {0, 0} }, // HT_DIR_HU
3012 { {1, 0}, {1, 1} }, // HT_DIR_HL
3013 { {1, 0}, {1, 1} }, // HT_DIR_VL
3014 { {0, 1}, {1, 1} }, // HT_DIR_VR
3015 };
3016 static const std::pair<TileIndexDiffC, TileIndexDiffC> end_heightdiff_line_by_dir[] = {
3017 { {0, 1}, {0, 0} }, // HT_DIR_X
3018 { {1, 0}, {0, 0} }, // HT_DIR_Y
3019 { {0, 1}, {0, 0} }, // HT_DIR_HU
3020 { {1, 1}, {0, 1} }, // HT_DIR_HL
3021 { {1, 0}, {0, 0} }, // HT_DIR_VL
3022 { {0, 0}, {0, 1} }, // HT_DIR_VR
3023 };
3024 static_assert(std::size(start_heightdiff_line_by_dir) == HT_DIR_END);
3025 static_assert(std::size(end_heightdiff_line_by_dir) == HT_DIR_END);
3026
3027 distance %= 2; // we're only interested if the distance is even or uneven
3028 style &= HT_DIR_MASK;
3029 assert(style < HT_DIR_END);
3030
3031 /* To handle autorail, we do some magic to be able to use a lookup table.
3032 * Firstly if we drag the other way around, we switch start&end, and if needed
3033 * also flip the drag-position. Eg if it was on the left, and the distance is even
3034 * that means the end, which is now the start is on the right */
3035 if (swap && distance == 0) style = flip_style_direction[style];
3036
3037 /* Lambda to help calculating the height at one side of the line. */
3038 auto get_height = [](auto &tile, auto &heightdiffs) {
3039 return std::max(
3040 TileHeight(TileAdd(tile, ToTileIndexDiff(heightdiffs.first))),
3041 TileHeight(TileAdd(tile, ToTileIndexDiff(heightdiffs.second))));
3042 };
3043
3044 /* Use lookup table for start-tile based on HighLightStyle direction */
3045 h0 = get_height(start_tile, start_heightdiff_line_by_dir[style]);
3046
3047 /* Use lookup table for end-tile based on HighLightStyle direction
3048 * flip around side (lower/upper, left/right) based on distance */
3049 if (distance == 0) style = flip_style_direction[style];
3050 h1 = get_height(end_tile, end_heightdiff_line_by_dir[style]);
3051 break;
3052 }
3053 }
3054
3055 if (swap) std::swap(h0, h1);
3056 return (int)(h1 - h0) * TILE_HEIGHT_STEP;
3057}
3058
3065static void CheckUnderflow(int &test, int &other, int mult)
3066{
3067 if (test >= 0) return;
3068
3069 other += mult * test;
3070 test = 0;
3071}
3072
3080static void CheckOverflow(int &test, int &other, int max, int mult)
3081{
3082 if (test <= max) return;
3083
3084 other += mult * (test - max);
3085 test = max;
3086}
3087
3094static void CalcRaildirsDrawstyle(int x, int y, int method)
3095{
3097
3098 int dx = _thd.selstart.x - (_thd.selend.x & ~TILE_UNIT_MASK);
3099 int dy = _thd.selstart.y - (_thd.selend.y & ~TILE_UNIT_MASK);
3100 uint w = abs(dx) + TILE_SIZE;
3101 uint h = abs(dy) + TILE_SIZE;
3102
3103 if (method & ~(VPM_RAILDIRS | VPM_SIGNALDIRS)) {
3104 /* We 'force' a selection direction; first four rail buttons. */
3105 method &= ~(VPM_RAILDIRS | VPM_SIGNALDIRS);
3106 int raw_dx = _thd.selstart.x - _thd.selend.x;
3107 int raw_dy = _thd.selstart.y - _thd.selend.y;
3108 switch (method) {
3109 case VPM_FIX_X:
3110 b = HT_LINE | HT_DIR_Y;
3111 x = _thd.selstart.x;
3112 break;
3113
3114 case VPM_FIX_Y:
3115 b = HT_LINE | HT_DIR_X;
3116 y = _thd.selstart.y;
3117 break;
3118
3119 case VPM_FIX_HORIZONTAL:
3120 if (dx == -dy) {
3121 /* We are on a straight horizontal line. Determine the 'rail'
3122 * to build based the sub tile location. */
3124 } else {
3125 /* We are not on a straight line. Determine the rail to build
3126 * based on whether we are above or below it. */
3127 b = dx + dy >= (int)TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
3128
3129 /* Calculate where a horizontal line through the start point and
3130 * a vertical line from the selected end point intersect and
3131 * use that point as the end point. */
3132 int offset = (raw_dx - raw_dy) / 2;
3133 x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
3134 y = _thd.selstart.y + (offset & ~TILE_UNIT_MASK);
3135
3136 /* 'Build' the last half rail tile if needed */
3137 if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
3138 if (dx + dy >= (int)TILE_SIZE) {
3139 x -= (int)TILE_SIZE;
3140 } else {
3141 y += (int)TILE_SIZE;
3142 }
3143 }
3144
3145 /* Make sure we do not overflow the map! */
3146 CheckUnderflow(x, y, 1);
3147 CheckUnderflow(y, x, 1);
3148 CheckOverflow(x, y, (Map::MaxX() - 1) * TILE_SIZE, 1);
3149 CheckOverflow(y, x, (Map::MaxY() - 1) * TILE_SIZE, 1);
3150 assert(x >= 0 && y >= 0 && x <= (int)(Map::MaxX() * TILE_SIZE) && y <= (int)(Map::MaxY() * TILE_SIZE));
3151 }
3152 break;
3153
3154 case VPM_FIX_VERTICAL:
3155 if (dx == dy) {
3156 /* We are on a straight vertical line. Determine the 'rail'
3157 * to build based the sub tile location. */
3159 } else {
3160 /* We are not on a straight line. Determine the rail to build
3161 * based on whether we are left or right from it. */
3162 b = dx < dy ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
3163
3164 /* Calculate where a vertical line through the start point and
3165 * a horizontal line from the selected end point intersect and
3166 * use that point as the end point. */
3167 int offset = (raw_dx + raw_dy + (int)TILE_SIZE) / 2;
3168 x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
3169 y = _thd.selstart.y - (offset & ~TILE_UNIT_MASK);
3170
3171 /* 'Build' the last half rail tile if needed */
3172 if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
3173 if (dx < dy) {
3174 y -= (int)TILE_SIZE;
3175 } else {
3176 x -= (int)TILE_SIZE;
3177 }
3178 }
3179
3180 /* Make sure we do not overflow the map! */
3181 CheckUnderflow(x, y, -1);
3182 CheckUnderflow(y, x, -1);
3183 CheckOverflow(x, y, (Map::MaxX() - 1) * TILE_SIZE, -1);
3184 CheckOverflow(y, x, (Map::MaxY() - 1) * TILE_SIZE, -1);
3185 assert(x >= 0 && y >= 0 && x <= (int)(Map::MaxX() * TILE_SIZE) && y <= (int)(Map::MaxY() * TILE_SIZE));
3186 }
3187 break;
3188
3189 default:
3190 NOT_REACHED();
3191 }
3192 } else if (TileVirtXY(_thd.selstart.x, _thd.selstart.y) == TileVirtXY(x, y)) { // check if we're only within one tile
3193 if (method & VPM_RAILDIRS) {
3194 b = GetAutorailHT(x, y);
3195 } else { // rect for autosignals on one tile
3196 b = HT_RECT;
3197 }
3198 } else if (h == TILE_SIZE) { // Is this in X direction?
3199 if (dx == (int)TILE_SIZE) { // 2x1 special handling
3201 } else if (dx == -(int)TILE_SIZE) {
3203 } else {
3204 b = HT_LINE | HT_DIR_X;
3205 }
3206 y = _thd.selstart.y;
3207 } else if (w == TILE_SIZE) { // Or Y direction?
3208 if (dy == (int)TILE_SIZE) { // 2x1 special handling
3210 } else if (dy == -(int)TILE_SIZE) { // 2x1 other direction
3212 } else {
3213 b = HT_LINE | HT_DIR_Y;
3214 }
3215 x = _thd.selstart.x;
3216 } else if (w > h * 2) { // still count as x dir?
3217 b = HT_LINE | HT_DIR_X;
3218 y = _thd.selstart.y;
3219 } else if (h > w * 2) { // still count as y dir?
3220 b = HT_LINE | HT_DIR_Y;
3221 x = _thd.selstart.x;
3222 } else { // complicated direction
3223 int d = w - h;
3224 _thd.selend.x = _thd.selend.x & ~TILE_UNIT_MASK;
3225 _thd.selend.y = _thd.selend.y & ~TILE_UNIT_MASK;
3226
3227 /* four cases. */
3228 if (x > _thd.selstart.x) {
3229 if (y > _thd.selstart.y) {
3230 /* south */
3231 if (d == 0) {
3233 } else if (d >= 0) {
3234 x = _thd.selstart.x + h;
3235 b = HT_LINE | HT_DIR_VL;
3236 } else {
3237 y = _thd.selstart.y + w;
3238 b = HT_LINE | HT_DIR_VR;
3239 }
3240 } else {
3241 /* west */
3242 if (d == 0) {
3244 } else if (d >= 0) {
3245 x = _thd.selstart.x + h;
3246 b = HT_LINE | HT_DIR_HL;
3247 } else {
3248 y = _thd.selstart.y - w;
3249 b = HT_LINE | HT_DIR_HU;
3250 }
3251 }
3252 } else {
3253 if (y > _thd.selstart.y) {
3254 /* east */
3255 if (d == 0) {
3257 } else if (d >= 0) {
3258 x = _thd.selstart.x - h;
3259 b = HT_LINE | HT_DIR_HU;
3260 } else {
3261 y = _thd.selstart.y + w;
3262 b = HT_LINE | HT_DIR_HL;
3263 }
3264 } else {
3265 /* north */
3266 if (d == 0) {
3268 } else if (d >= 0) {
3269 x = _thd.selstart.x - h;
3270 b = HT_LINE | HT_DIR_VR;
3271 } else {
3272 y = _thd.selstart.y - w;
3273 b = HT_LINE | HT_DIR_VL;
3274 }
3275 }
3276 }
3277 }
3278
3279 if (_settings_client.gui.measure_tooltip) {
3280 TileIndex t0 = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
3281 TileIndex t1 = TileVirtXY(x, y);
3282 uint distance = DistanceManhattan(t0, t1) + 1;
3283
3284 if (distance == 1) {
3285 HideMeasurementTooltips();
3286 } else {
3287 int heightdiff = CalcHeightdiff(b, distance, t0, t1);
3288 /* If we are showing a tooltip for horizontal or vertical drags,
3289 * 2 tiles have a length of 1. To bias towards the ceiling we add
3290 * one before division. It feels more natural to count 3 lengths as 2 */
3291 if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
3292 distance = CeilDiv(distance, 2);
3293 }
3294
3295 if (heightdiff == 0) {
3296 ShowMeasurementTooltips(GetEncodedString(STR_MEASURE_LENGTH, distance));
3297 } else {
3298 ShowMeasurementTooltips(GetEncodedString(STR_MEASURE_LENGTH_HEIGHTDIFF, distance, heightdiff));
3299 }
3300 }
3301 }
3302
3303 _thd.selend.x = x;
3304 _thd.selend.y = y;
3305 _thd.next_drawstyle = b;
3306}
3307
3316{
3317 int sx, sy;
3318 HighLightStyle style;
3319
3320 if (x == -1) {
3321 _thd.selend.x = -1;
3322 return;
3323 }
3324
3325 /* Special handling of drag in any (8-way) direction */
3326 if (method & (VPM_RAILDIRS | VPM_SIGNALDIRS)) {
3327 _thd.selend.x = x;
3328 _thd.selend.y = y;
3329 CalcRaildirsDrawstyle(x, y, method);
3330 return;
3331 }
3332
3333 /* Needed so level-land is placed correctly */
3334 if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_POINT) {
3335 x += TILE_SIZE / 2;
3336 y += TILE_SIZE / 2;
3337 }
3338
3339 sx = _thd.selstart.x;
3340 sy = _thd.selstart.y;
3341
3342 int limit = 0;
3343
3344 switch (method) {
3345 case VPM_X_OR_Y: // drag in X or Y direction
3346 if (abs(sy - y) < abs(sx - x)) {
3347 y = sy;
3348 style = HT_DIR_X;
3349 } else {
3350 x = sx;
3351 style = HT_DIR_Y;
3352 }
3353 goto calc_heightdiff_single_direction;
3354
3355 case VPM_X_LIMITED: // Drag in X direction (limited size).
3356 limit = (_thd.sizelimit - 1) * TILE_SIZE;
3357 [[fallthrough]];
3358
3359 case VPM_FIX_X: // drag in Y direction
3360 x = sx;
3361 style = HT_DIR_Y;
3362 goto calc_heightdiff_single_direction;
3363
3364 case VPM_Y_LIMITED: // Drag in Y direction (limited size).
3365 limit = (_thd.sizelimit - 1) * TILE_SIZE;
3366 [[fallthrough]];
3367
3368 case VPM_FIX_Y: // drag in X direction
3369 y = sy;
3370 style = HT_DIR_X;
3371
3372calc_heightdiff_single_direction:;
3373 if (limit > 0) {
3374 x = sx + Clamp(x - sx, -limit, limit);
3375 y = sy + Clamp(y - sy, -limit, limit);
3376 }
3377 if (_settings_client.gui.measure_tooltip) {
3378 TileIndex t0 = TileVirtXY(sx, sy);
3379 TileIndex t1 = TileVirtXY(x, y);
3380 uint distance = DistanceManhattan(t0, t1) + 1;
3381
3382 if (distance == 1) {
3383 HideMeasurementTooltips();
3384 } else {
3385 /* With current code passing a HT_LINE style to calculate the height
3386 * difference is enough. However if/when a point-tool is created
3387 * with this method, function should be called with new_style (below)
3388 * instead of HT_LINE | style case HT_POINT is handled specially
3389 * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
3390 int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
3391
3392 if (heightdiff == 0) {
3393 ShowMeasurementTooltips(GetEncodedString(STR_MEASURE_LENGTH, distance));
3394 } else {
3395 ShowMeasurementTooltips(GetEncodedString(STR_MEASURE_LENGTH_HEIGHTDIFF, distance, heightdiff));
3396 }
3397 }
3398 }
3399 break;
3400
3401 case VPM_X_AND_Y_LIMITED: // Drag an X by Y constrained rect area.
3402 limit = (_thd.sizelimit - 1) * TILE_SIZE;
3403 x = sx + Clamp(x - sx, -limit, limit);
3404 y = sy + Clamp(y - sy, -limit, limit);
3405 [[fallthrough]];
3406
3407 case VPM_X_AND_Y: // drag an X by Y area
3408 if (_settings_client.gui.measure_tooltip) {
3409 TileIndex t0 = TileVirtXY(sx, sy);
3410 TileIndex t1 = TileVirtXY(x, y);
3411 uint dx = Delta(TileX(t0), TileX(t1)) + 1;
3412 uint dy = Delta(TileY(t0), TileY(t1)) + 1;
3413
3414 /* If dragging an area (eg dynamite tool) and it is actually a single
3415 * row/column, change the type to 'line' to get proper calculation for height */
3416 style = (HighLightStyle)_thd.next_drawstyle;
3417 if (_thd.IsDraggingDiagonal()) {
3418 /* Determine the "area" of the diagonal dragged selection.
3419 * We assume the area is the number of tiles along the X
3420 * edge and the number of tiles along the Y edge. However,
3421 * multiplying these two numbers does not give the exact
3422 * number of tiles; basically we are counting the black
3423 * squares on a chess board and ignore the white ones to
3424 * make the tile counts at the edges match up. There is no
3425 * other way to make a proper count though.
3426 *
3427 * First convert to the rotated coordinate system. */
3428 int dist_x = TileX(t0) - TileX(t1);
3429 int dist_y = TileY(t0) - TileY(t1);
3430 int a_max = dist_x + dist_y;
3431 int b_max = dist_y - dist_x;
3432
3433 /* Now determine the size along the edge, but due to the
3434 * chess board principle this counts double. */
3435 a_max = abs(a_max + (a_max > 0 ? 2 : -2)) / 2;
3436 b_max = abs(b_max + (b_max > 0 ? 2 : -2)) / 2;
3437
3438 /* We get a 1x1 on normal 2x1 rectangles, due to it being
3439 * a seen as two sides. As the result for actual building
3440 * will be the same as non-diagonal dragging revert to that
3441 * behaviour to give it a more normally looking size. */
3442 if (a_max != 1 || b_max != 1) {
3443 dx = a_max;
3444 dy = b_max;
3445 }
3446 } else if (style & HT_RECT) {
3447 if (dx == 1) {
3448 style = HT_LINE | HT_DIR_Y;
3449 } else if (dy == 1) {
3450 style = HT_LINE | HT_DIR_X;
3451 }
3452 }
3453
3454 if (dx != 1 || dy != 1) {
3455 int heightdiff = CalcHeightdiff(style, 0, t0, t1);
3456
3457 dx -= (style & HT_POINT ? 1 : 0);
3458 dy -= (style & HT_POINT ? 1 : 0);
3459
3460 if (heightdiff == 0) {
3461 ShowMeasurementTooltips(GetEncodedString(STR_MEASURE_AREA, dx, dy));
3462 } else {
3463 ShowMeasurementTooltips(GetEncodedString(STR_MEASURE_AREA_HEIGHTDIFF, dx, dy, heightdiff));
3464 }
3465 }
3466 }
3467 break;
3468
3469 default: NOT_REACHED();
3470 }
3471
3472 _thd.selend.x = x;
3473 _thd.selend.y = y;
3474}
3475
3481{
3483
3484 /* stop drag mode if the window has been closed */
3485 Window *w = _thd.GetCallbackWnd();
3486 if (w == nullptr) {
3488 return EventState::Handled;
3489 }
3490
3491 /* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
3492 if (IsLeftButtonDown()) {
3494 /* Only register a drag event when the mouse moved. */
3495 if (_thd.new_pos.x == _thd.selstart.x && _thd.new_pos.y == _thd.selstart.y) return EventState::Handled;
3496 _thd.selstart.x = _thd.new_pos.x;
3497 _thd.selstart.y = _thd.new_pos.y;
3498 }
3499
3500 w->OnPlaceDrag(_thd.select_method, _thd.select_proc, GetTileBelowCursor());
3501 return EventState::Handled;
3502 }
3503
3504 /* Mouse button released. */
3507
3508 /* Keep the selected tool, but reset it to the original mode. */
3509 HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
3510 if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_RECT) {
3511 _thd.place_mode = HT_RECT | others;
3512 } else if (_thd.select_method & VPM_SIGNALDIRS) {
3513 _thd.place_mode = HT_RECT | others;
3514 } else if (_thd.select_method & VPM_RAILDIRS) {
3515 _thd.place_mode = (_thd.select_method & ~VPM_RAILDIRS) ? _thd.next_drawstyle : (HT_RAIL | others);
3516 } else {
3517 _thd.place_mode = HT_POINT | others;
3518 }
3519 SetTileSelectSize(1, 1);
3520
3521 HideMeasurementTooltips();
3522 w->OnPlaceMouseUp(_thd.select_method, _thd.select_proc, _thd.selend, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y));
3523
3524 return EventState::Handled;
3525}
3526
3535{
3536 SetObjectToPlace(icon, pal, mode, w->window_class, w->window_number);
3537}
3538
3539#include "table/animcursors.h"
3540
3549void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
3550{
3551 if (_thd.window_class != WindowClass::Invalid) {
3552 /* Undo clicking on button and drag & drop */
3553 Window *w = _thd.GetCallbackWnd();
3554 /* Call the abort function, but set the window class to something
3555 * that will never be used to avoid infinite loops. Setting it to
3556 * the 'next' window class must not be done because recursion into
3557 * this function might in some cases reset the newly set object to
3558 * place or not properly reset the original selection. */
3559 _thd.window_class = WindowClass::Invalid;
3560 if (w != nullptr) {
3561 w->OnPlaceObjectAbort();
3562 HideMeasurementTooltips();
3563 }
3564 }
3565
3566 /* Mark the old selection dirty, in case the selection shape or colour changes */
3567 if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
3568
3569 SetTileSelectSize(1, 1);
3570
3571 _thd.make_square_red = false;
3572
3573 if (mode == HT_DRAG) { // HT_DRAG is for dragdropping trains in the depot window
3574 mode = HT_NONE;
3576 } else {
3578 }
3579
3580 _thd.place_mode = mode;
3581 _thd.window_class = window_class;
3582 _thd.window_number = window_num;
3583
3584 if ((mode & HT_DRAG_MASK) == HT_SPECIAL) { // special tools, like tunnels or docks start with presizing mode
3585 VpStartPreSizing();
3586 }
3587
3588 SetCursor(icon, pal);
3589}
3590
3593{
3594 SetObjectToPlace(SPR_CURSOR_MOUSE, PAL_NONE, HT_NONE, WindowClass::MainWindow, 0);
3595}
3596
3597Point GetViewportStationMiddle(const Viewport &vp, const Station *st)
3598{
3599 int x = TileX(st->xy) * TILE_SIZE;
3600 int y = TileY(st->xy) * TILE_SIZE;
3601 int z = GetSlopePixelZ(Clamp(x, 0, Map::SizeX() * TILE_SIZE - 1), Clamp(y, 0, Map::SizeY() * TILE_SIZE - 1));
3602
3603 Point p = RemapCoords(x, y, z);
3604 p.x = UnScaleByZoom(p.x - vp.virtual_left, vp.zoom) + vp.left;
3605 p.y = UnScaleByZoom(p.y - vp.virtual_top, vp.zoom) + vp.top;
3606 return p;
3607}
3608
3614
3617#ifdef WITH_SSE
3618 { &ViewportSortParentSpritesSSE41Checker, &ViewportSortParentSpritesSSE41 },
3619#endif
3620 { []() { return true; /* Always available */ }, &ViewportSortParentSprites }
3621};
3622
3625{
3626 for (const auto &sprite_sorter : _vp_sprite_sorters) {
3627 if (sprite_sorter.fct_checker()) {
3628 _vp_sprite_sorter = sprite_sorter.fct_sorter;
3629 break;
3630 }
3631 }
3632 assert(_vp_sprite_sorter != nullptr);
3633}
3634
3644{
3645 if (_current_company != OWNER_DEITY) return CMD_ERROR;
3646 switch (target) {
3648 break;
3650 if (_local_company != (CompanyID)ref) return CommandCost();
3651 break;
3653 if (_network_own_client_id != (ClientID)ref) return CommandCost();
3654 break;
3655 default:
3656 return CMD_ERROR;
3657 }
3658
3659 if (flags.Test(DoCommandFlag::Execute)) {
3662 }
3663 return CommandCost();
3664}
3665
3666void MarkCatchmentTilesDirty()
3667{
3668 if (_viewport_highlight_town != nullptr) {
3670 return;
3671 }
3672
3673 if (_viewport_highlight_station != nullptr) {
3674 if (_viewport_highlight_station->catchment_tiles.IsEmpty()) {
3677 } else {
3678 for (TileIndex tile : _viewport_highlight_station->catchment_tiles) {
3679 MarkTileDirtyByTile(tile);
3680 }
3681 }
3682 }
3683
3684 if (_viewport_highlight_station_rect != nullptr) {
3685 if (!_viewport_highlight_station_rect->IsInUse()) {
3687 }
3689 }
3690
3691 if (_viewport_highlight_waypoint != nullptr) {
3692 if (!_viewport_highlight_waypoint->IsInUse()) {
3694 }
3696 }
3697
3698 if (_viewport_highlight_waypoint_rect != nullptr) {
3699 if (!_viewport_highlight_waypoint_rect->IsInUse()) {
3701 }
3703 }
3704}
3705
3706static void SetWindowDirtyForViewportCatchment()
3707{
3708 if (_viewport_highlight_station != nullptr) SetWindowDirty(WindowClass::StationView, _viewport_highlight_station->index);
3709 if (_viewport_highlight_station_rect != nullptr) SetWindowDirty(WindowClass::StationView, _viewport_highlight_station_rect->index);
3710 if (_viewport_highlight_waypoint != nullptr) SetWindowDirty(WindowClass::WaypointView, _viewport_highlight_waypoint->index);
3711 if (_viewport_highlight_waypoint_rect != nullptr) SetWindowDirty(WindowClass::WaypointView, _viewport_highlight_waypoint_rect->index);
3712 if (_viewport_highlight_town != nullptr) SetWindowDirty(WindowClass::TownView, _viewport_highlight_town->index);
3713}
3714
3715static void ClearViewportCatchment()
3716{
3717 MarkCatchmentTilesDirty();
3722 _viewport_highlight_town = nullptr;
3723}
3724
3731void SetViewportCatchmentStation(const Station *st, bool sel)
3732{
3733 SetWindowDirtyForViewportCatchment();
3734 /* Mark tiles dirty for redrawing and update selected station if a different station is already highlighted. */
3735 if (sel && _viewport_highlight_station != st) {
3736 ClearViewportCatchment();
3738 MarkCatchmentTilesDirty();
3739 /* Mark tiles dirty for redrawing and clear station selection if deselecting highlight. */
3740 } else if (!sel && _viewport_highlight_station == st) {
3741 MarkCatchmentTilesDirty();
3743 }
3744 /* Redraw the currently selected station window */
3745 if (_viewport_highlight_station != nullptr) SetWindowDirty(WindowClass::StationView, _viewport_highlight_station->index);
3746}
3747
3754void SetViewportStationRect(const Station *st, bool sel)
3755{
3756 SetWindowDirtyForViewportCatchment();
3757 /* Mark tiles dirty for redrawing and update selected station if a different station is already highlighted. */
3758 if (sel && _viewport_highlight_station_rect != st) {
3759 ClearViewportCatchment();
3761 MarkCatchmentTilesDirty();
3762 /* Mark tiles dirty for redrawing and clear station selection if deselecting highlight. */
3763 } else if (!sel && _viewport_highlight_station_rect == st) {
3764 MarkCatchmentTilesDirty();
3766 }
3767 /* Redraw the currently selected station window */
3768 if (_viewport_highlight_station_rect != nullptr) SetWindowDirty(WindowClass::StationView, _viewport_highlight_station_rect->index);
3769}
3770
3778{
3779 SetWindowDirtyForViewportCatchment();
3780 /* Mark tiles dirty for redrawing and update selected waypoint if a different waypoint is already highlighted. */
3781 if (sel && _viewport_highlight_waypoint != wp) {
3782 ClearViewportCatchment();
3784 MarkCatchmentTilesDirty();
3785 /* Mark tiles dirty for redrawing and clear waypoint selection if deselecting highlight. */
3786 } else if (!sel && _viewport_highlight_waypoint == wp) {
3787 MarkCatchmentTilesDirty();
3789 }
3790 /* Redraw the currently selected waypoint window */
3791 if (_viewport_highlight_waypoint != nullptr) SetWindowDirty(WindowClass::WaypointView, _viewport_highlight_waypoint->index);
3792}
3793
3800void SetViewportWaypointRect(const Waypoint *wp, bool sel)
3801{
3802 SetWindowDirtyForViewportCatchment();
3803 /* Mark tiles dirty for redrawing and update selected waypoint if a different waypoint is already highlighted. */
3804 if (sel && _viewport_highlight_waypoint_rect != wp) {
3805 ClearViewportCatchment();
3807 MarkCatchmentTilesDirty();
3808 /* Mark tiles dirty for redrawing and clear waypoint selection if deselecting highlight. */
3809 } else if (!sel && _viewport_highlight_waypoint_rect == wp) {
3810 MarkCatchmentTilesDirty();
3812 }
3813 /* Redraw the currently selected waypoint window */
3814 if (_viewport_highlight_waypoint_rect != nullptr) SetWindowDirty(WindowClass::WaypointView, _viewport_highlight_waypoint_rect->index);
3815}
3816
3823void SetViewportCatchmentTown(const Town *t, bool sel)
3824{
3825 SetWindowDirtyForViewportCatchment();
3826 /* Mark tiles dirty for redrawing and update selected town if a different town is already highlighted. */
3827 if (sel && _viewport_highlight_town != t) {
3828 ClearViewportCatchment();
3831 /* Mark tiles dirty for redrawing and clear town selection if deselecting highlight. */
3832 } else if (!sel && _viewport_highlight_town == t) {
3833 _viewport_highlight_town = nullptr;
3835 }
3836 /* Redraw the currently selected town window */
3837 if (_viewport_highlight_town != nullptr) SetWindowDirty(WindowClass::TownView, _viewport_highlight_town->index);
3838}
3839
3844void ViewportData::CancelFollow(const Window &viewport_window)
3845{
3846 if (this->follow_vehicle == VehicleID::Invalid()) return;
3847
3848 if (viewport_window.window_class == WindowClass::MainWindow) {
3849 /* We're cancelling follow in the main viewport, so we need to check for a vehicle view window
3850 * to raise the location follow widget. */
3851 Window *vehicle_window = FindWindowById(WindowClass::VehicleView, this->follow_vehicle);
3852 if (vehicle_window != nullptr) vehicle_window->RaiseWidgetWhenLowered(WID_VV_LOCATION);
3853 }
3854
3855 this->dest_scrollpos_x = this->scrollpos_x;
3856 this->dest_scrollpos_y = this->scrollpos_y;
3857 this->follow_vehicle = VehicleID::Invalid();
3858}
This file defines all the the animated cursors.
Highlight/sprite information for autorail.
static constexpr SlopeIndexArray< std::array< int, 6 > > _autorail_slope_sprite_offsets
Table maps each of the six rail directions and tileh combinations to a sprite offset.
Definition autorail.h:25
static const HighLightStyle _autorail_piece[][16]
Maps each pixel of a tile (16x16) to a selection type (0,0) is the top corner, (16,...
Definition autorail.h:63
Class for backupping variables and making sure they are restored later.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
TileIndex GetNorthernBridgeEnd(TileIndex t)
Finds the northern end of a bridge starting at a middle tile.
Map accessor functions for bridges.
int GetBridgePixelHeight(TileIndex tile)
Get the height ('z') of a bridge in pixels.
Definition bridge_map.h:84
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition bridge_map.h:45
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Set()
Set all bits.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:139
How all blitters should look like.
Definition base.hpp:28
virtual void * MoveTo(void *video, int x, int y)=0
Move the destination pointer the requested amount x and y, keeping in mind any pitch and bpp of the r...
virtual void SetPixel(void *video, int x, int y, PixelColour colour)=0
Draw a pixel with a given colour on the video-buffer.
Common return value for all commands.
Container for an encoded string, created by GetEncodedString.
Iterate a range of enum values.
RAII class for measuring multi-step elements of performance.
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
TypedIndexContainer< std::array< Colours, MAX_COMPANIES >, CompanyID > _company_colours
NOSAVE: can be determined from company structs.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
static constexpr Owner OWNER_DEITY
The object is owned by a superuser / goal script.
static constexpr Owner OWNER_NONE
The tile has no ownership.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Warning
Warning, wrong but okay if you don't know.
Definition debug_type.h:17
@ SW
Southwest.
@ SE
Southeast.
DiagDirection
Enumeration for diagonal directions.
@ SW
Southwest.
@ NW
Northwest.
@ NE
Northeast, upper right on your monitor.
@ SE
Southeast.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Factory to 'query' all available blitters.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
Types for recording game performance data.
@ ViewportDrawing
Time spent drawing world viewports in GUI.
@ Centre
Align to the centre.
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
void SetCursor(CursorID icon, PaletteID pal)
Assign an animation or a non-animated sprite to the cursor.
Definition gfx.cpp:1732
void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
Draw a sprite in a viewport.
Definition gfx.cpp:1004
void DrawBox(int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
Draws the projection of a parallelepiped.
Definition gfx.cpp:421
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
bool IsLeftButtonDown()
Test if the left mouse button is pressed.
Definition gfx_func.h:70
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
@ Normal
The most basic (normal) sprite.
Definition gfx_type.h:405
@ Small
Index of the small font in the font tables.
Definition gfx_type.h:250
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
uint32_t CursorID
The number of the cursor (sprite).
Definition gfx_type.h:19
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
Colours
One of 16 base colours used for companies and windows/widgets.
Definition gfx_type.h:283
@ White
White.
Definition gfx_type.h:300
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ Grey
Grey.
Definition gfx_type.h:299
@ White
White colour.
Definition gfx_type.h:330
@ Black
Black colour.
Definition gfx_type.h:334
@ Town
Destination is a town.
Definition goal_type.h:55
static const CursorID SPR_CURSOR_MOUSE
Definition sprites.h:1568
bool MarkAllViewportsDirty(int left, int top, int right, int bottom)
Mark all viewports that display an area as dirty (in need of repaint).
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
void AddDirtyBlock(int left, int top, int right, int bottom)
Extend the internal _invalid_rect rectangle to contain the rectangle defined by the given parameters.
Definition gfx.cpp:1515
void MarkDirty(ZoomLevel maxzoom=ZoomLevel::Max) const
Mark the sign dirty in all viewports.
static bool MarkViewportDirty(const Viewport &vp, int left, int top, int right, int bottom)
Marks a viewport as dirty for repaint if it displays (a part of) the area the needs to be repainted.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
void RedrawScreenRect(int left, int top, int right, int bottom)
Repaints a specific rectangle of the screen.
Definition gfx.cpp:1425
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static void SetSelectionTilesDirty()
Marks the selected tiles as dirty.
Point InverseRemapCoords2(int x, int y, bool clamp_to_map, bool *clamped)
Map 2D viewport or smallmap coordinate to 3D world or tile coordinate.
const EnumIndexArray< const TileTypeProcs *, TileType, TileType::MaxSize > _tile_type_procs
Tile callback functions for each type of tile.
Definition landscape.cpp:71
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
Functions related to OTTD's landscape.
Point RemapCoords(int x, int y, int z)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:81
Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:97
Point InverseRemapCoords(int x, int y)
Map 2D viewport or smallmap coordinate to 3D world or tile coordinate.
Definition landscape.h:111
Declaration of linkgraph overlay GUI.
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
Zooms a viewport in a window in or out.
Definition main_gui.cpp:88
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:168
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:407
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition map_func.h:603
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition map_func.h:444
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:376
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
constexpr TileIndex TileAdd(TileIndex tile, TileIndexDiff offset)
Adds a given offset to a tile.
Definition map_func.h:461
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition math_func.hpp:37
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Delta(const T a, const T b)
Returns the (absolute) difference between two (scalar) variables.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
void GuiShowTooltips(Window *parent, EncodedString &&text, TooltipCloseCondition close_tooltip)
Shows a tooltip.
Definition misc_gui.cpp:690
ClientID _network_own_client_id
Our client identifier.
Definition network.cpp:68
Network functions used by other parts of OpenTTD.
ClientID
'Unique' identifier to be given to clients
@ ShowSigns
Display signs.
Definition openttd.h:48
@ ShowWaypointNames
Display waypoint names.
Definition openttd.h:51
@ ShowTownNames
Display town names.
Definition openttd.h:46
@ ShowStationNames
Display station names.
Definition openttd.h:47
@ ShowCompetitorSigns
Display signs, station names and waypoint names of opponent companies. Buoys and oilrig-stations are ...
Definition openttd.h:52
@ Menu
In the main menu.
Definition openttd.h:19
PixelColour GetColourGradient(Colours colour, Shade shade)
Get colour gradient palette index.
Definition palette.cpp:393
@ Lighter
Lighter colour shade.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Base class for signs.
Functions related to signs.
void HandleClickOnSign(const Sign *si)
Handle clicking on a sign.
PoolID< uint16_t, struct SignIDTag, 64000, 0xFFFF > SignID
The type of the IDs of signs.
Definition signs_type.h:16
Slope SlopeWithThreeCornersRaised(Corner corner)
Returns the slope with all except one corner raised.
Definition slope_func.h:216
Corner OppositeCorner(Corner corner)
Returns the opposite corner.
Definition slope_func.h:194
static constexpr Corner GetHalftileSlopeCorner(Slope s)
Returns the leveled halftile of a halftile slope.
Definition slope_func.h:158
static constexpr Slope RemoveHalftileSlope(Slope s)
Removes a halftile slope from a slope.
Definition slope_func.h:70
uint SlopeToSpriteOffset(Slope s)
Returns the Sprite offset for a given Slope.
Definition slope_func.h:423
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition slope_func.h:36
static constexpr bool IsHalftileSlope(Slope s)
Checks for non-continuous slope on halftile foundations.
Definition slope_func.h:57
Slope SlopeWithOneCornerRaised(Corner corner)
Returns the slope with a specific corner raised.
Definition slope_func.h:109
Corner
Enumeration of tile corners.
Definition slope_type.h:21
@ E
East tile corner.
Definition slope_type.h:24
@ S
South tile corner.
Definition slope_type.h:23
@ W
West tile corner.
Definition slope_type.h:22
Slope
Enumeration for the slope-type.
Definition slope_type.h:53
@ SLOPE_N
the north corner of the tile is raised
Definition slope_type.h:58
@ SLOPE_STEEP_N
a steep slope falling to south (from north)
Definition slope_type.h:74
EnumIndexArray< T, Corner, Corner::End > CornerIndexArray
Array with Corner as index.
Definition slope_type.h:35
bool ScrollMainWindowTo(int x, int y, int z, bool instant)
Scrolls the main window to given coordinates.
Functions to cache sprites in memory.
static const SpriteID SPR_DOT
Corner marker for lower/raise land.
Definition sprites.h:45
static constexpr uint32_t MAX_SPRITES
Masks needed for sprite operations.
Definition sprites.h:1742
static const PaletteID PALETTE_TILE_RED_PULSATING
pulsating red tile drawn if you try to build a wrong tunnel or raise/lower land where it is not possi...
Definition sprites.h:1756
static const PaletteID PALETTE_SEL_TILE_RED
makes a square red. is used when removing rails or other stuff
Definition sprites.h:1757
static constexpr uint32_t SPRITE_MASK
The mask to for the main sprite.
Definition sprites.h:1743
static constexpr uint8_t PALETTE_MODIFIER_TRANSPARENT
when a sprite is to be displayed transparently, this bit needs to be set.
Definition sprites.h:1734
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1794
static const PaletteID PALETTE_SEL_TILE_BLUE
This draws a blueish square (catchment areas for example).
Definition sprites.h:1758
static const SpriteID SPR_HALFTILE_SELECTION_FLAT
Definition sprites.h:66
static const SpriteID SPR_HALFTILE_SELECTION_UP
Definition sprites.h:68
static const SpriteID SPR_HALFTILE_SELECTION_DOWN
Definition sprites.h:67
static const PaletteID PALETTE_TO_TRANSPARENT
This sets the sprite to transparent.
Definition sprites.h:1791
static const SpriteID SPR_EMPTY_BOUNDING_BOX
Definition sprites.h:339
Base classes/functions for stations.
Functions related to stations.
void ShowStationViewWindow(StationID station)
Opens StationViewWindow for given station.
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:26
Definition of base types and functions in a cross-platform compatible way.
@ Sign
Use the Sign cursor.
Definition story_base.h:56
The colour translation of GRF's strings.
static constexpr PixelColour _string_colourmap[17]
Colour mapping for TextColour.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Base class for all station-ish types.
TileIndex xy
Base tile of the station.
Owner owner
The owner of this station.
TrackedViewportSign sign
NOSAVE: Dimensions of sign.
int next
next child to draw (-1 at the end)
Definition viewport.cpp:141
const SubSprite * sub
only draw a rectangular part of the sprite
Definition viewport.cpp:137
T y
Y coordinate.
T x
X coordinate.
T x
X coordinate.
T y
Y coordinate.
T z
Z coordinate.
Data about how and where to blit pixels.
Definition gfx_type.h:157
Container for the text colour and some text colour related flags for drawing.
Definition gfx_type.h:349
static uint SizeX()
Get the size of the map along the X.
Definition map_func.h:262
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:271
static uint ScaleBySize1D(uint n)
Scales the given value by the maps circumference, where the given value is for a 256 by 256 map.
Definition map_func.h:344
static uint MaxY()
Gets the maximum Y coordinate within the map, including TileType::Void.
Definition map_func.h:298
static uint MaxX()
Gets the maximum X coordinate within the map, including TileType::Void.
Definition map_func.h:289
Parent sprite that should be drawn.
const SubSprite * sub
only draw a rectangular part of the sprite
int32_t zmin
minimal world Z coordinate of bounding box
SpriteID image
sprite to draw
int32_t xmax
maximal world X coordinate of bounding box
int32_t ymax
maximal world Y coordinate of bounding box
int32_t x
screen X coordinate of sprite
int32_t y
screen Y coordinate of sprite
int32_t first_child
the first child to draw.
int32_t zmax
maximal world Z coordinate of bounding box
int32_t xmin
minimal world X coordinate of bounding box
int32_t ymin
minimal world Y coordinate of bounding box
PaletteID pal
palette to use
int32_t left
minimal screen X coordinate of sprite (= x + sprite->x_offs), reference point for child sprites
int32_t top
minimal screen Y coordinate of sprite (= y + sprite->y_offs), reference point for child sprites
Colour for pixel/line drawing.
Definition gfx_type.h:307
static Pool::IterateWrapper< Town > Iterate(size_t from=0)
static Vehicle * Get(auto index)
Specification of a rectangle with absolute coordinates of all edges.
static bool IsExpected(const BaseStation *st)
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static Station * Get(auto index)
static Waypoint * From(BaseStation *st)
Coord3D< int8_t > offset
Relative position of sprite from bounding box.
Definition sprite.h:21
Coord3D< int8_t > origin
Position of northern corner within tile.
Definition sprite.h:19
Coord3D< uint8_t > extent
Size of bounding box.
Definition sprite.h:20
Data structure describing a sprite.
uint16_t width
Width of the sprite.
uint16_t height
Height of the sprite.
int16_t y_offs
Number of pixels to shift the sprite downwards.
int16_t x_offs
Number of pixels to shift the sprite to the right.
Station data structure.
Used to only draw a part of the sprite.
Definition gfx_type.h:278
Metadata about the current highlighting.
Point new_pos
New value for pos; used to determine whether to redraw the selection.
Window * GetCallbackWnd()
Get the window that started the current highlighting.
bool IsDraggingDiagonal()
Is the user dragging a 'diagonal rectangle'?
HighLightStyle place_mode
Method which is used to place the selection.
WindowClass window_class
The WindowClass of the window that is responsible for the selection mode.
Point pos
Location, in tile "units", of the northern tile of the selected area.
void Reset()
Reset tile highlighting.
WindowNumber window_number
The WindowNumber of the window that is responsible for the selection mode.
Tile information, used while rendering the tile.
Definition tile_cmd.h:34
Slope tileh
Slope of the tile.
Definition tile_cmd.h:35
TileIndex tile
Tile index.
Definition tile_cmd.h:36
int32_t y
screen Y coordinate of sprite
Definition viewport.cpp:131
int32_t x
screen X coordinate of sprite
Definition viewport.cpp:130
const SubSprite * sub
only draw a rectangular part of the sprite
Definition viewport.cpp:129
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition town.h:55
Town data structure.
Definition town.h:64
TileIndex xy
town center tile
Definition town.h:65
TownCache cache
Container for all cacheable data.
Definition town.h:67
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition town.h:202
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Vehicle data structure.
int32_t z_pos
z coordinate.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
Owner owner
Which company owns the vehicle?
UnitID unitnumber
unit number, for display purposes only
Data structure for a window viewport.
Definition window_gui.h:249
void CancelFollow(const Window &viewport_window)
Cancel viewport vehicle following, and raise follow location widget if needed.
int32_t dest_scrollpos_y
Current destination y coordinate to display (virtual screen coordinate of topleft corner of the viewp...
Definition window_gui.h:254
int32_t scrollpos_y
Currently shown y coordinate (virtual screen coordinate of topleft corner of the viewport).
Definition window_gui.h:252
int32_t dest_scrollpos_x
Current destination x coordinate to display (virtual screen coordinate of topleft corner of the viewp...
Definition window_gui.h:253
VehicleID follow_vehicle
VehicleID to follow if following a vehicle, VehicleID::Invalid() otherwise.
Definition window_gui.h:250
int32_t scrollpos_x
Currently shown x coordinate (virtual screen coordinate of topleft corner of the viewport).
Definition window_gui.h:251
Data structure storing rendering information.
Definition viewport.cpp:171
ParentSpriteToSortVector parent_sprites_to_sort
Parent sprite pointer array used for sorting.
Definition viewport.cpp:177
EnumIndexArray< Point, FoundationPart, FoundationPart::End > foundation_offset
Pixel offset for ground sprites on the foundations.
Definition viewport.cpp:187
EnumIndexArray< int, FoundationPart, FoundationPart::End > foundation
Foundation sprites (index into parent_sprites_to_draw).
Definition viewport.cpp:185
SpriteCombineMode combine_sprites
Current mode of "sprite combining".
Definition viewport.cpp:182
EnumIndexArray< int, FoundationPart, FoundationPart::End > last_foundation_child
Tail of ChildSprite list of the foundations. (index into child_screen_sprites_to_draw).
Definition viewport.cpp:186
FoundationPart foundation_part
Currently active foundation for ground sprite drawing.
Definition viewport.cpp:184
Helper class for getting the best sprite sorter.
VpSorterChecker fct_checker
The check function.
VpSpriteSorter fct_sorter
The sorting function.
Location information about a sign as seen on the viewport.
int32_t center
The center position of the sign.
uint16_t width_small
The width when zoomed out (small font).
uint16_t width_normal
The width when not zoomed out (normal font).
void UpdatePosition(int center, int top, std::string_view str, std::string_view str_small={})
Update the position of the viewport sign.
int32_t top
The top of the sign.
Data structure for viewport, display of a part of the world.
int top
Screen coordinate top edge of the viewport.
int width
Screen width of the viewport.
ZoomLevel zoom
The zoom level of the viewport.
int virtual_top
Virtual top coordinate.
int virtual_left
Virtual left coordinate.
int virtual_width
width << zoom
int left
Screen coordinate left edge of the viewport.
int height
Screen height of the viewport.
int virtual_height
height << zoom
Representation of a waypoint.
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
std::unique_ptr< ViewportData > viewport
Pointer to viewport data, if present.
Definition window_gui.h:317
void RaiseWidgetWhenLowered(WidgetID widget_index)
Marks a widget as raised and dirty (redraw), when it is marked as lowered.
Definition window_gui.h:477
virtual void OnPlaceObjectAbort()
The user cancelled a tile highlight mode that has been set.
Definition window_gui.h:848
WindowClass window_class
Window class.
Definition window_gui.h:300
void DrawViewport() const
Draw the viewport of this window.
virtual void OnPlaceObject(Point pt, TileIndex tile)
The user clicked some place on the map when a tile highlight mode has been set.
Definition window_gui.h:826
WindowIterator< false > IteratorToFront
Iterate in Z order towards front.
Definition window_gui.h:937
int left
x position of left edge of the window
Definition window_gui.h:308
int top
y position of top edge of the window
Definition window_gui.h:309
virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile)
The user has dragged over the map when the tile highlight mode has been set.
Definition window_gui.h:869
virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt)
The user is dragging over the map when the tile highlight mode has been set.
Definition window_gui.h:858
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
AllWindows< false > Iterate
Iterate all windows in whatever order is easiest.
Definition window_gui.h:959
int height
Height of the window (number of pixels down in y direction).
Definition window_gui.h:311
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
std::tuple< Slope, int > GetTilePixelSlopeOutsideMap(int x, int y)
Return the slope of a given tile, also for tiles outside the map (virtual "black" tiles).
Definition tile_map.cpp:77
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
static uint TileHeight(Tile tile)
Returns the height of a tile.
Definition tile_map.h:29
int GetTilePixelZ(TileIndex tile)
Get bottom height of the tile.
Definition tile_map.h:302
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition tile_map.h:312
std::tuple< Slope, int > GetTilePixelSlope(TileIndex tile)
Return the slope of a given tile.
Definition tile_map.h:289
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition tile_map.h:161
uint TilePixelHeight(Tile tile)
Returns the height of a tile in pixels.
Definition tile_map.h:72
uint TilePixelHeightOutsideMap(int x, int y)
Returns the height of a tile in pixels, also for tiles outside the map (virtual "black" tiles).
Definition tile_map.h:84
static TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition tile_map.h:96
uint TileHeightOutsideMap(int x, int y)
Returns the height of a tile, also for tiles outside the map (virtual "black" tiles).
Definition tile_map.h:42
static constexpr uint TILE_UNIT_MASK
For masking in/out the inner-tile world coordinate units.
Definition tile_type.h:16
static constexpr uint MAX_BUILDING_PIXELS
Maximum height of a building in pixels in ZOOM_BASE. (Also applies to "bridge buildings" on the bridg...
Definition tile_type.h:20
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
static constexpr uint TILE_PIXELS
Pixel distance between tile columns/rows in ZOOM_BASE.
Definition tile_type.h:17
static constexpr uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
Definition tile_type.h:18
TileType
The different types of tiles.
Definition tile_type.h:48
@ Station
A tile of a station or airport.
Definition tile_type.h:54
@ Void
Invisible tiles at the SW and SE border.
Definition tile_type.h:56
@ House
A house by a town.
Definition tile_type.h:52
Functions related to tile highlights.
HighLightStyle
Highlighting draw styles.
@ HT_LINE
used for autorail highlighting (longer stretches), lower bits: direction
@ HT_DIR_HL
horizontal lower
@ HT_DIR_HU
horizontal upper
@ HT_DRAG
dragging items in the depot windows
@ HT_NONE
default
@ HT_DIR_X
X direction.
@ HT_DIAGONAL
Also allow 'diagonal rectangles'. Only usable in combination with HT_RECT or HT_POINT.
@ HT_POINT
point (lower land, raise land, level land, ...)
@ HT_RECT
rectangle (stations, depots, ...)
@ HT_DIR_MASK
masks the drag-direction
@ HT_RAIL
autorail (one piece), lower bits: direction
@ HT_DIR_END
end marker
@ HT_DRAG_MASK
Mask for the tile drag-type modes.
@ HT_DIR_VL
vertical left
@ HT_VEHICLE
vehicle is accepted as target as well (bitmask)
@ HT_DIR_VR
vertical right
@ HT_SPECIAL
special mode used for highlighting while dragging (and for tunnels/docks)
@ HT_DIR_Y
Y direction.
Base of the town class.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Declarations for accessing the k-d tree of towns.
TownID GetTownIndex(Tile t)
Get the index of which town this house/street is attached to.
Definition town_map.h:23
bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
DisplayOptions _display_opt
What do we want to draw/do?
void ViewportAddVehicles(DrawPixelInfo *dpi)
Add the vehicle sprites that should be drawn at a part of the screen.
Definition vehicle.cpp:1150
Vehicle * CheckClickOnVehicle(const Viewport &vp, int x, int y)
Find the vehicle close to the clicked coordinates.
Definition vehicle.cpp:1244
Base class for all vehicles.
Functions related to vehicles.
bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
void ShowVehicleViewWindow(const Vehicle *v)
Shows the vehicle view window of the given vehicle.
bool VehicleClicked(const Vehicle *v)
Dispatch a "vehicle selected" event if any window waits for it.
void StartStopVehicle(const Vehicle *v, bool texteffect)
Executes Commands::StartStopVehicle for given vehicle.
Functions related to the vehicle's GUIs.
Types related to the vehicle widgets.
@ WID_VV_LOCATION
Center the main view on this vehicle.
static void HighlightTownLocalAuthorityTiles(const TileInfo *ti)
Highlights tiles inside local authority of selected towns.
std::string * ViewportAddString(const DrawPixelInfo *dpi, const ViewportSign *sign, ViewportStringFlags flags, Colours colour)
Add a string to draw in the current viewport.
static void CheckOverflow(int &test, int &other, int max, int mult)
Check for overflowing the map.
bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
Scrolls the viewport in a window to a given location.
FoundationPart
Enumeration of multi-part foundations.
Definition viewport.cpp:145
@ None
Neither foundation nor groundsprite drawn yet.
Definition viewport.cpp:146
@ End
End marker.
Definition viewport.cpp:149
@ Normal
First part (normal foundation or no foundation).
Definition viewport.cpp:147
@ Halftile
Second part (halftile foundation).
Definition viewport.cpp:148
void SetTileSelectSize(int w, int h)
Highlight w by h tiles at the cursor.
CommandCost CmdScrollViewport(DoCommandFlags flags, TileIndex tile, ViewportScrollTarget target, uint32_t ref)
Scroll players main viewport.
static void ViewportAddStationStrings(DrawPixelInfo *dpi, const std::vector< const BaseStation * > &stations, bool small)
Add station strings to a viewport.
static void DrawAutorailSelection(const TileInfo *ti, HighLightStyle highlight_style)
Draws autorail highlights.
Definition viewport.cpp:977
void OffsetGroundSprite(int x, int y)
Called when a foundation has been drawn for the current tile.
Definition viewport.cpp:606
constexpr int LAST_CHILD_NONE
There is no last_child to fill.
Definition viewport.cpp:167
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
static void ViewportAddSignStrings(DrawPixelInfo *dpi, const std::vector< const Sign * > &signs, bool small)
Add sign strings to a viewport.
void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
constexpr int LAST_CHILD_PARENT
Fill last_child of the most recent parent sprite.
Definition viewport.cpp:168
static const int MAX_TILE_EXTENT_TOP
Maximum top extent of tile relative to north corner (not considering bridges).
Definition viewport.cpp:114
void SetViewportStationRect(const Station *st, bool sel)
Select or deselect station for rectangle area highlight.
static void ShowMeasurementTooltips(EncodedString &&text)
Displays the measurement tooltips when selecting multiple tiles.
static const int MAX_TILE_EXTENT_LEFT
Maximum left extent of tile relative to north corner.
Definition viewport.cpp:112
bool IsInsideRotatedRectangle(int x, int y)
Checks whether a point is inside the selected a diagonal rectangle given by _thd.size and _thd....
Definition viewport.cpp:804
static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
Calculates height difference between one tile and another.
static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
Draws a selection rectangle on a tile.
Definition viewport.cpp:917
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
Definition viewport.cpp:766
void InitializeSpriteSorter()
Choose the "best" sprite sorter and set _vp_sprite_sorter.
static const ViewportSSCSS _vp_sprite_sorters[]
List of sorters ordered from best to worst.
static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, int z, const SubSprite *sub)
Adds a child sprite to a parent sprite.
Definition viewport.cpp:630
static int GetViewportY(Point tile)
Returns the y coordinate in the viewport coordinate system where the given tile is painted.
static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
Adds a child sprite to the active foundation.
Definition viewport.cpp:533
static HighLightStyle GetAutorailHT(int x, int y)
Determine the best autorail highlight type from map coordinates.
static void ClampSmoothScroll(uint32_t delta_ms, int64_t delta_hi, int64_t delta_lo, int &delta_hi_clamped, int &delta_lo_clamped)
Clamp the smooth scroll to a maximum speed and distance based on time elapsed.
static void DrawTileSelection(const TileInfo *ti)
Checks if the specified tile is selected and if so draws selection using correct selectionstyle.
static TileHighlightType GetTileHighlightType(TileIndex t)
Get tile highlight type of coverage area for a given tile.
static bool IsInRangeInclusive(int begin, int end, int check)
Check if the parameter "check" is inside the interval between begin and end, including both begin and...
Definition viewport.cpp:792
const Waypoint * _viewport_highlight_waypoint_rect
Currently selected waypoint for rectangle highlight.
Point TranslateXYToTileCoord(const Viewport &vp, int x, int y, bool clamp_to_map)
Translate screen coordinate in a viewport to underlying tile coordinate.
Definition viewport.cpp:431
SpriteCombineMode
Mode of "sprite combining".
Definition viewport.cpp:156
@ Pending
Sprite combining will start with the next unclipped sprite.
Definition viewport.cpp:158
@ Active
Sprite combining is active. AddSortableSpriteToDraw outputs child sprites.
Definition viewport.cpp:159
@ None
Every AddSortableSpriteToDraw start its own bounding box.
Definition viewport.cpp:157
static void DrawTileHighlightType(const TileInfo *ti, TileHighlightType tht)
Draw tile highlight for coverage area highlight.
static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
Draws the bounding boxes of all ParentSprites.
static void ViewportAddTownStrings(DrawPixelInfo *dpi, const std::vector< const Town * > &towns, bool small)
Add town strings to a viewport.
void SetViewportCatchmentWaypoint(const Waypoint *wp, bool sel)
Select or deselect waypoint for coverage area highlight.
void SetRedErrorSquare(TileIndex tile)
Set a tile to display a red error square.
static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
Sort parent sprites pointer array replicating the way original sorter did it.
void VpSetPresizeRange(TileIndex from, TileIndex to)
Highlights all tiles between a set of two tiles.
static HighLightStyle Check2x1AutoRail(DiagDirection direction)
What would be the highlight style when trying to build a 2 tile long piece of rail.
TileHighlightType
Types of tile highlight.
@ White
Indicates a tile which is part of the highlighted station, or a station tile within the highlighted t...
@ None
No tile highlight.
@ Blue
Indicates a tile which is in the catchment area of the highlighted station.
@ Red
Indicates a house tile which is not in any station catchment area of the highlighted town.
void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
Selects tiles while dragging.
EventState VpHandlePlaceSizingDrag()
Handle the mouse while dragging for placement/resizing.
Viewport * IsPtInWindowViewport(const Window *w, int x, int y)
Is a xy position inside the viewport of the window?
Definition viewport.cpp:409
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int z, const SpriteBounds &bounds, bool transparent, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition viewport.cpp:665
void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Definition viewport.cpp:776
static const int MAX_TILE_EXTENT_RIGHT
Maximum right extent of tile relative to north corner.
Definition viewport.cpp:113
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale, bool relative)
Add a child sprite to a parent sprite.
Definition viewport.cpp:827
static void CheckUnderflow(int &test, int &other, int mult)
Check for underflowing the map.
void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32_t x, int32_t y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite at a specific world-coordinate relative to the current tile.
Definition viewport.cpp:557
void VpStartDragging(ViewportDragDropSelectionProcess process)
Drag over the map while holding the left mouse down.
void UpdateTileSelection()
Updates tile highlighting for all cases.
static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part, int extra_offs_x=0, int extra_offs_y=0)
Draws sprites between ground sprite and everything above.
Definition viewport.cpp:900
static const int MAX_TILE_EXTENT_BOTTOM
Maximum bottom extent of tile relative to north corner (worst case: SLOPE_STEEP_N).
Definition viewport.cpp:115
static bool CheckClickOnViewportSign(const Viewport &vp, int x, int y, const ViewportSign *sign)
Test whether a sign is below the mouse.
void SetViewportCatchmentStation(const Station *st, bool sel)
Select or deselect station for coverage area highlight.
void SetViewportCatchmentTown(const Town *t, bool sel)
Select or deselect town for coverage area highlight.
static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
Check if the direction of start and end tile should be swapped based on the dragging-style.
void InitializeWindowViewport(Window *w, int x, int y, int width, int height, std::variant< TileIndex, VehicleID > focus, ZoomLevel zoom)
Initialize viewport of the window for use.
Definition viewport.cpp:219
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition viewport.cpp:580
static void CalcRaildirsDrawstyle(int x, int y, int method)
Determine and set the draw style, as well as the end point of the drag.
static FoundationPart GetNextFoundationPart(FoundationPart foundation_part)
Get the next foundation part.
Definition viewport.cpp:590
void SetViewportWaypointRect(const Waypoint *wp, bool sel)
Select or deselect waypoint for rectangle area highlight.
static void ViewportDrawDirtyBlocks()
Draw/colour the blocks that have been redrawn.
void HandleZoomMessage(Window *w, const Viewport &vp, WidgetID widget_zoom_in, WidgetID widget_zoom_out)
Update the status of the zoom-buttons according to the zoom-level of the viewport.
Definition viewport.cpp:487
void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
Prepare state for highlighting tiles while dragging with the mouse.
const Station * _viewport_highlight_station_rect
Currently selected station for rectangle highlight.
static void ClampViewportToMap(const Viewport &vp, int *scroll_x, int *scroll_y)
Ensure that a given viewport has a valid scroll position.
static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32_t x, int32_t y, int z, const SubSprite *sub=nullptr, int extra_offs_x=0, int extra_offs_y=0)
Schedules a tile sprite for drawing.
Definition viewport.cpp:508
static void ViewportAddLandscape()
Add the landscape to the viewport, i.e.
static std::string & AddStringToDraw(int x, int y, Colours colour, ViewportStringFlags flags, uint16_t width)
Add a string to draw to a viewport.
Definition viewport.cpp:873
const Station * _viewport_highlight_station
Currently selected station for coverage area highlight.
const Town * _viewport_highlight_town
Currently selected town for coverage area highlight.
void UpdateViewportPosition(Window *w, uint32_t delta_ms)
Update the viewport position being displayed.
const Waypoint * _viewport_highlight_waypoint
Currently selected waypoint for coverage area highlight.
bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
Scrolls the viewport in a window to a given location.
Command definitions related to viewports.
Functions related to (drawing on) viewports.
static const int TILE_HEIGHT_STEP
One Z unit tile height difference is displayed as 50m.
Declarations for accessing the k-d tree of viewports.
Types related to sprite sorting.
bool(* VpSorterChecker)()
Type for method for checking whether a viewport sprite sorter exists.
void(* VpSpriteSorter)(ParentSpriteToSortVector *psd)
Type for the actual viewport sprite sorter.
ViewportScrollTarget
Target of the viewport scrolling GS method.
@ Company
All players in specific company.
@ Client
Single player.
@ Everyone
All players.
ViewportPlaceMethod
Viewport place method (type of highlighted area and placed objects).
@ VPM_FIX_Y
drag only in Y axis
@ VPM_Y_LIMITED
Drag only in Y axis with limited size.
@ VPM_X_AND_Y_LIMITED
area of land of limited size
@ VPM_FIX_VERTICAL
drag only in vertical direction
@ VPM_X_LIMITED
Drag only in X axis with limited size.
@ VPM_X_AND_Y
area of land in X and Y directions
@ VPM_FIX_HORIZONTAL
drag only in horizontal direction
@ VPM_FIX_X
drag only in X axis
@ VPM_SIGNALDIRS
similar to VMP_RAILDIRS, but with different cursor
@ VPM_X_OR_Y
drag in X or Y direction
@ VPM_RAILDIRS
all rail directions
@ ZOOM_IN
Zoom in (get more detailed view).
@ ZOOM_OUT
Zoom out (get helicopter view).
ViewportDragDropSelectionProcess
Drag and drop selection process, or, what to do with an area of land when you've selected it.
@ ColourRect
Draw a colour rect around the sign.
@ Small
Draw using the small font.
@ Shadow
Draw an extra text shadow. Should only be used with ViewportStringFlag::Small, as normal font already...
@ TransparentRect
Draw a transparent rect around the sign.
@ TextColour
Draw text in colour.
EnumBitSet< ViewportStringFlag, uint8_t > ViewportStringFlags
Bitset of ViewportStringFlag elements.
Base of waypoints.
Functions related to waypoints.
void ShowWaypointWindow(const Waypoint *wp)
Show the window for the given waypoint.
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
Draw frame rectangle.
Definition widget.cpp:308
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
Window * GetMainWindow()
Get the main window, i.e.
Definition window.cpp:1228
Window * FindWindowFromPt(int x, int y)
Do a search for a window at specific coordinates.
Definition window.cpp:1891
SpecialMouseMode _special_mouse_mode
Mode of the mouse.
Definition window.cpp:91
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1199
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
@ ExitViewport
Close the tooltip when leaving the viewport.
Definition window_gui.h:266
@ Transparent
Makes the background transparent if set.
Definition window_gui.h:24
@ DragDrop
Drag&drop an object.
@ None
No special mouse mode.
@ Dragging
Dragging mode (trees).
@ Sizing
Sizing mode.
@ Presize
Presizing mode (docks, tunnels).
int WidgetID
Widget ID.
Definition window_type.h:21
EventState
State of handling an event.
@ Handled
The passed event is handled.
@ NotHandled
The passed event is not handled.
@ Waypoint
waypoint encountered (could be a target next time)
Definition yapf_type.hpp:25
@ Station
station encountered (could be a target next time)
Definition yapf_type.hpp:26
Functions related to zooming.
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:22
int UnScaleByZoomLower(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZoomLevel::Min).
Definition zoom_func.h:67
int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:34
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:20
@ Min
Minimum zoom level.
Definition zoom_type.h:23
@ End
End for iteration.
Definition zoom_type.h:31
@ Out4x
Zoomed 4 times out.
Definition zoom_type.h:28