Add: Overlay cargo icon in vehicle/depot list when holding shift+ctrl. (#12938)
[openttd-github.git] / src / smallmap_gui.cpp
blobe3daba039da7bb472a65bd07996da0ca767f6176
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file smallmap_gui.cpp GUI that shows a small map of the world with metadata like owner or height. */
10 #include "stdafx.h"
11 #include "core/backup_type.hpp"
12 #include "clear_map.h"
13 #include "industry.h"
14 #include "station_map.h"
15 #include "landscape.h"
16 #include "tree_map.h"
17 #include "viewport_func.h"
18 #include "town.h"
19 #include "tunnelbridge_map.h"
20 #include "core/endian_func.hpp"
21 #include "vehicle_base.h"
22 #include "sound_func.h"
23 #include "window_func.h"
24 #include "company_base.h"
25 #include "zoom_func.h"
26 #include "strings_func.h"
27 #include "blitter/factory.hpp"
28 #include "linkgraph/linkgraph_gui.h"
29 #include "timer/timer.h"
30 #include "timer/timer_window.h"
31 #include "smallmap_gui.h"
33 #include "widgets/smallmap_widget.h"
35 #include "table/strings.h"
37 #include <bitset>
39 #include "safeguards.h"
41 static int _smallmap_industry_count; ///< Number of used industries
42 static int _smallmap_company_count; ///< Number of entries in the owner legend.
43 static int _smallmap_cargo_count; ///< Number of cargos in the link stats legend.
45 /** Structure for holding relevant data for legends in small map */
46 struct LegendAndColour {
47 uint8_t colour; ///< Colour of the item on the map.
48 StringID legend; ///< String corresponding to the coloured item.
49 IndustryType type; ///< Type of industry. Only valid for industry entries.
50 uint8_t height; ///< Height in tiles. Only valid for height legend entries.
51 CompanyID company; ///< Company to display. Only valid for company entries of the owner legend.
52 bool show_on_map; ///< For filtering industries, if \c true, industry is shown on the map in colour.
53 bool end; ///< This is the end of the list.
54 bool col_break; ///< Perform a column break and go further at the next column.
57 /** Link stat colours shown in legenda. */
58 static uint8_t _linkstat_colours_in_legenda[] = {0, 1, 3, 5, 7, 9, 11};
60 static const int NUM_NO_COMPANY_ENTRIES = 4; ///< Number of entries in the owner legend that are not companies.
62 /** Macro for ordinary entry of LegendAndColour */
63 #define MK(a, b) {a, b, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, false}
65 /** Macro for a height legend entry with configurable colour. */
66 #define MC(col_break) {0, STR_TINY_BLACK_HEIGHT, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, col_break}
68 /** Macro for non-company owned property entry of LegendAndColour */
69 #define MO(a, b) {a, b, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, false}
71 /** Macro used for forcing a rebuild of the owner legend the first time it is used. */
72 #define MOEND() {0, 0, INVALID_INDUSTRYTYPE, 0, OWNER_NONE, true, true, false}
74 /** Macro for end of list marker in arrays of LegendAndColour */
75 #define MKEND() {0, STR_NULL, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, true, false}
77 /**
78 * Macro for break marker in arrays of LegendAndColour.
79 * It will have valid data, though
81 #define MS(a, b) {a, b, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, true}
83 /** Legend text giving the colours to look for on the minimap */
84 static LegendAndColour _legend_land_contours[] = {
85 MK(PC_BLACK, STR_SMALLMAP_LEGENDA_ROADS),
86 MK(PC_GREY, STR_SMALLMAP_LEGENDA_RAILROADS),
87 MK(PC_LIGHT_BLUE, STR_SMALLMAP_LEGENDA_STATIONS_AIRPORTS_DOCKS),
88 MK(PC_DARK_RED, STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
89 MK(PC_WHITE, STR_SMALLMAP_LEGENDA_VEHICLES),
91 /* Placeholders for the colours and heights of the legend.
92 * The following values are set at BuildLandLegend() based
93 * on each colour scheme and the maximum map height. */
94 MC(true),
95 MC(false),
96 MC(false),
97 MC(false),
98 MC(false),
99 MC(false),
100 MC(true),
101 MC(false),
102 MC(false),
103 MC(false),
104 MC(false),
105 MC(false),
106 MKEND()
109 static const LegendAndColour _legend_vehicles[] = {
110 MK(PC_RED, STR_SMALLMAP_LEGENDA_TRAINS),
111 MK(PC_YELLOW, STR_SMALLMAP_LEGENDA_ROAD_VEHICLES),
112 MK(PC_LIGHT_BLUE, STR_SMALLMAP_LEGENDA_SHIPS),
113 MK(PC_WHITE, STR_SMALLMAP_LEGENDA_AIRCRAFT),
115 MS(PC_BLACK, STR_SMALLMAP_LEGENDA_TRANSPORT_ROUTES),
116 MK(PC_DARK_RED, STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
117 MKEND()
120 static const LegendAndColour _legend_routes[] = {
121 MK(PC_BLACK, STR_SMALLMAP_LEGENDA_ROADS),
122 MK(PC_GREY, STR_SMALLMAP_LEGENDA_RAILROADS),
123 MK(PC_DARK_RED, STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
125 MS(PC_VERY_DARK_BROWN, STR_SMALLMAP_LEGENDA_RAILROAD_STATION),
126 MK(PC_ORANGE, STR_SMALLMAP_LEGENDA_TRUCK_LOADING_BAY),
127 MK(PC_YELLOW, STR_SMALLMAP_LEGENDA_BUS_STATION),
128 MK(PC_RED, STR_SMALLMAP_LEGENDA_AIRPORT_HELIPORT),
129 MK(PC_LIGHT_BLUE, STR_SMALLMAP_LEGENDA_DOCK),
130 MKEND()
133 static const LegendAndColour _legend_vegetation[] = {
134 MK(PC_ROUGH_LAND, STR_SMALLMAP_LEGENDA_ROUGH_LAND),
135 MK(PC_GRASS_LAND, STR_SMALLMAP_LEGENDA_GRASS_LAND),
136 MK(PC_BARE_LAND, STR_SMALLMAP_LEGENDA_BARE_LAND),
137 MK(PC_RAINFOREST, STR_SMALLMAP_LEGENDA_RAINFOREST),
138 MK(PC_FIELDS, STR_SMALLMAP_LEGENDA_FIELDS),
139 MK(PC_TREES, STR_SMALLMAP_LEGENDA_TREES),
141 MS(PC_GREEN, STR_SMALLMAP_LEGENDA_FOREST),
142 MK(PC_GREY, STR_SMALLMAP_LEGENDA_ROCKS),
143 MK(PC_ORANGE, STR_SMALLMAP_LEGENDA_DESERT),
144 MK(PC_LIGHT_BLUE, STR_SMALLMAP_LEGENDA_SNOW),
145 MK(PC_BLACK, STR_SMALLMAP_LEGENDA_TRANSPORT_ROUTES),
146 MK(PC_DARK_RED, STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
147 MKEND()
150 static LegendAndColour _legend_land_owners[NUM_NO_COMPANY_ENTRIES + MAX_COMPANIES + 1] = {
151 MO(PC_WATER, STR_SMALLMAP_LEGENDA_WATER),
152 MO(0x00, STR_SMALLMAP_LEGENDA_NO_OWNER), // This colour will vary depending on settings.
153 MO(PC_DARK_RED, STR_SMALLMAP_LEGENDA_TOWNS),
154 MO(PC_DARK_GREY, STR_SMALLMAP_LEGENDA_INDUSTRIES),
155 /* The legend will be terminated the first time it is used. */
156 MOEND(),
159 #undef MK
160 #undef MC
161 #undef MS
162 #undef MO
163 #undef MOEND
164 #undef MKEND
166 /** Legend entries for the link stats view. */
167 static LegendAndColour _legend_linkstats[NUM_CARGO + lengthof(_linkstat_colours_in_legenda) + 1];
169 * Allow room for all industries, plus a terminator entry
170 * This is required in order to have the industry slots all filled up
172 static LegendAndColour _legend_from_industries[NUM_INDUSTRYTYPES + 1];
173 /** For connecting industry type to position in industries list(small map legend) */
174 static uint _industry_to_list_pos[NUM_INDUSTRYTYPES];
175 /** The string bounding box width for each industry type in the smallmap */
176 static uint16_t _industry_to_name_string_width[NUM_INDUSTRYTYPES];
177 /** Show heightmap in industry and owner mode of smallmap window. */
178 static bool _smallmap_show_heightmap = false;
179 /** Highlight a specific industry type */
180 static IndustryType _smallmap_industry_highlight = INVALID_INDUSTRYTYPE;
181 /** State of highlight blinking */
182 static bool _smallmap_industry_highlight_state;
183 /** For connecting company ID to position in owner list (small map legend) */
184 static uint _company_to_list_pos[MAX_COMPANIES];
187 * Fills an array for the industries legends.
189 void BuildIndustriesLegend()
191 uint j = 0;
193 /* Add each name */
194 for (IndustryType ind : _sorted_industry_types) {
195 const IndustrySpec *indsp = GetIndustrySpec(ind);
196 if (indsp->enabled) {
197 _legend_from_industries[j].legend = indsp->name;
198 _legend_from_industries[j].colour = indsp->map_colour;
199 _legend_from_industries[j].type = ind;
200 _legend_from_industries[j].show_on_map = true;
201 _legend_from_industries[j].col_break = false;
202 _legend_from_industries[j].end = false;
204 /* Store widget number for this industry type. */
205 _industry_to_list_pos[ind] = j;
206 j++;
209 /* Terminate the list */
210 _legend_from_industries[j].end = true;
212 /* Store number of enabled industries */
213 _smallmap_industry_count = j;
217 * Populate legend table for the link stat view.
219 void BuildLinkStatsLegend()
221 /* Clear the legend */
222 memset(_legend_linkstats, 0, sizeof(_legend_linkstats));
224 uint i = 0;
225 for (; i < _sorted_cargo_specs.size(); ++i) {
226 const CargoSpec *cs = _sorted_cargo_specs[i];
228 _legend_linkstats[i].legend = cs->name;
229 _legend_linkstats[i].colour = cs->legend_colour;
230 _legend_linkstats[i].type = cs->Index();
231 _legend_linkstats[i].show_on_map = true;
234 _legend_linkstats[i].col_break = true;
235 _smallmap_cargo_count = i;
237 for (; i < _smallmap_cargo_count + lengthof(_linkstat_colours_in_legenda); ++i) {
238 _legend_linkstats[i].legend = STR_EMPTY;
239 _legend_linkstats[i].colour = LinkGraphOverlay::LINK_COLOURS[_settings_client.gui.linkgraph_colours][_linkstat_colours_in_legenda[i - _smallmap_cargo_count]];
240 _legend_linkstats[i].show_on_map = true;
243 _legend_linkstats[_smallmap_cargo_count].legend = STR_LINKGRAPH_LEGEND_UNUSED;
244 _legend_linkstats[i - 1].legend = STR_LINKGRAPH_LEGEND_OVERLOADED;
245 _legend_linkstats[(_smallmap_cargo_count + i - 1) / 2].legend = STR_LINKGRAPH_LEGEND_SATURATED;
246 _legend_linkstats[i].end = true;
249 static const LegendAndColour * const _legend_table[] = {
250 _legend_land_contours,
251 _legend_vehicles,
252 _legend_from_industries,
253 _legend_linkstats,
254 _legend_routes,
255 _legend_vegetation,
256 _legend_land_owners,
259 #define MKCOLOUR(x) TO_LE32X(x)
261 #define MKCOLOUR_XXXX(x) (MKCOLOUR(0x01010101) * (uint)(x))
262 #define MKCOLOUR_X0X0(x) (MKCOLOUR(0x01000100) * (uint)(x))
263 #define MKCOLOUR_0X0X(x) (MKCOLOUR(0x00010001) * (uint)(x))
264 #define MKCOLOUR_0XX0(x) (MKCOLOUR(0x00010100) * (uint)(x))
265 #define MKCOLOUR_X00X(x) (MKCOLOUR(0x01000001) * (uint)(x))
267 #define MKCOLOUR_XYXY(x, y) (MKCOLOUR_X0X0(x) | MKCOLOUR_0X0X(y))
268 #define MKCOLOUR_XYYX(x, y) (MKCOLOUR_X00X(x) | MKCOLOUR_0XX0(y))
270 #define MKCOLOUR_0000 MKCOLOUR_XXXX(0x00)
271 #define MKCOLOUR_0FF0 MKCOLOUR_0XX0(0xFF)
272 #define MKCOLOUR_F00F MKCOLOUR_X00X(0xFF)
273 #define MKCOLOUR_FFFF MKCOLOUR_XXXX(0xFF)
275 #include "table/heightmap_colours.h"
277 /** Colour scheme of the smallmap. */
278 struct SmallMapColourScheme {
279 std::vector<uint32_t> height_colours; ///< Cached colours for each level in a map.
280 std::span<const uint32_t> height_colours_base; ///< Base table for determining the colours
281 uint32_t default_colour; ///< Default colour of the land.
284 /** Available colour schemes for height maps. */
285 static SmallMapColourScheme _heightmap_schemes[] = {
286 {{}, _green_map_heights, MKCOLOUR_XXXX(0x54)}, ///< Green colour scheme.
287 {{}, _dark_green_map_heights, MKCOLOUR_XXXX(0x62)}, ///< Dark green colour scheme.
288 {{}, _violet_map_heights, MKCOLOUR_XXXX(0x81)}, ///< Violet colour scheme.
292 * (Re)build the colour tables for the legends.
294 void BuildLandLegend()
296 /* The smallmap window has never been initialized, so no need to change the legend. */
297 if (_heightmap_schemes[0].height_colours.empty()) return;
300 * The general idea of this function is to fill the legend with an appropriate evenly spaced
301 * selection of height levels. All entries with STR_TINY_BLACK_HEIGHT are reserved for this.
302 * At the moment there are twelve of these.
304 * The table below defines up to which height level a particular delta in the legend should be
305 * used. One could opt for just dividing the maximum height and use that as delta, but that
306 * creates many "ugly" legend labels, e.g. once every 950 meter. As a result, this table will
307 * reduce the number of deltas to 7: every 100m, 200m, 300m, 500m, 750m, 1000m and 1250m. The
308 * deltas are closer together at the lower numbers because going from 12 entries to just 4, as
309 * would happen when replacing 200m and 300m by 250m, would mean the legend would be short and
310 * that might not be considered appropriate.
312 * The current method yields at least 7 legend entries and at most 12. It can be increased to
313 * 8 by adding a 150m and 400m option, but especially 150m creates ugly heights.
315 * It tries to evenly space the legend items over the two columns that are there for the legend.
318 /* Table for delta; if max_height is less than the first column, use the second column as value. */
319 uint deltas[][2] = { { 24, 2 }, { 48, 4 }, { 72, 6 }, { 120, 10 }, { 180, 15 }, { 240, 20 }, { MAX_TILE_HEIGHT + 1, 25 }};
320 uint i = 0;
321 for (; _settings_game.construction.map_height_limit >= deltas[i][0]; i++) {
322 /* Nothing to do here. */
324 uint delta = deltas[i][1];
326 int total_entries = (_settings_game.construction.map_height_limit / delta) + 1;
327 int rows = CeilDiv(total_entries, 2);
328 int j = 0;
330 for (i = 0; i < lengthof(_legend_land_contours) - 1 && j < total_entries; i++) {
331 if (_legend_land_contours[i].legend != STR_TINY_BLACK_HEIGHT) continue;
333 _legend_land_contours[i].col_break = j % rows == 0;
334 _legend_land_contours[i].end = false;
335 _legend_land_contours[i].height = j * delta;
336 _legend_land_contours[i].colour = _heightmap_schemes[_settings_client.gui.smallmap_land_colour].height_colours[j * delta];
337 j++;
339 _legend_land_contours[i].end = true;
343 * Completes the array for the owned property legend.
345 void BuildOwnerLegend()
347 _legend_land_owners[1].colour = _heightmap_schemes[_settings_client.gui.smallmap_land_colour].default_colour;
349 int i = NUM_NO_COMPANY_ENTRIES;
350 for (const Company *c : Company::Iterate()) {
351 _legend_land_owners[i].colour = GetColourGradient(c->colour, SHADE_LIGHT);
352 _legend_land_owners[i].company = c->index;
353 _legend_land_owners[i].show_on_map = true;
354 _legend_land_owners[i].col_break = false;
355 _legend_land_owners[i].end = false;
356 _company_to_list_pos[c->index] = i;
357 i++;
360 /* Terminate the list */
361 _legend_land_owners[i].end = true;
363 /* Store maximum amount of owner legend entries. */
364 _smallmap_company_count = i;
367 struct AndOr {
368 uint32_t mor;
369 uint32_t mand;
372 static inline uint32_t ApplyMask(uint32_t colour, const AndOr *mask)
374 return (colour & mask->mand) | mask->mor;
378 /** Colour masks for "Contour" and "Routes" modes. */
379 static const AndOr _smallmap_contours_andor[] = {
380 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_CLEAR
381 {MKCOLOUR_0XX0(PC_GREY ), MKCOLOUR_F00F}, // MP_RAILWAY
382 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F}, // MP_ROAD
383 {MKCOLOUR_0XX0(PC_DARK_RED ), MKCOLOUR_F00F}, // MP_HOUSE
384 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_TREES
385 {MKCOLOUR_XXXX(PC_LIGHT_BLUE), MKCOLOUR_0000}, // MP_STATION
386 {MKCOLOUR_XXXX(PC_WATER ), MKCOLOUR_0000}, // MP_WATER
387 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_VOID
388 {MKCOLOUR_XXXX(PC_DARK_RED ), MKCOLOUR_0000}, // MP_INDUSTRY
389 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_TUNNELBRIDGE
390 {MKCOLOUR_0XX0(PC_DARK_RED ), MKCOLOUR_F00F}, // MP_OBJECT
391 {MKCOLOUR_0XX0(PC_GREY ), MKCOLOUR_F00F},
394 /** Colour masks for "Vehicles", "Industry", and "Vegetation" modes. */
395 static const AndOr _smallmap_vehicles_andor[] = {
396 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_CLEAR
397 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F}, // MP_RAILWAY
398 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F}, // MP_ROAD
399 {MKCOLOUR_0XX0(PC_DARK_RED ), MKCOLOUR_F00F}, // MP_HOUSE
400 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_TREES
401 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F}, // MP_STATION
402 {MKCOLOUR_XXXX(PC_WATER ), MKCOLOUR_0000}, // MP_WATER
403 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_VOID
404 {MKCOLOUR_XXXX(PC_DARK_RED ), MKCOLOUR_0000}, // MP_INDUSTRY
405 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_TUNNELBRIDGE
406 {MKCOLOUR_0XX0(PC_DARK_RED ), MKCOLOUR_F00F}, // MP_OBJECT
407 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F},
410 /** Mapping of tile type to importance of the tile (higher number means more interesting to show). */
411 static const uint8_t _tiletype_importance[] = {
412 2, // MP_CLEAR
413 8, // MP_RAILWAY
414 7, // MP_ROAD
415 5, // MP_HOUSE
416 2, // MP_TREES
417 9, // MP_STATION
418 2, // MP_WATER
419 1, // MP_VOID
420 6, // MP_INDUSTRY
421 8, // MP_TUNNELBRIDGE
422 2, // MP_OBJECT
428 * Return the colour a tile would be displayed with in the small map in mode "Contour".
429 * @param tile The tile of which we would like to get the colour.
430 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
431 * @return The colour of tile in the small map in mode "Contour"
433 static inline uint32_t GetSmallMapContoursPixels(TileIndex tile, TileType t)
435 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
436 return ApplyMask(cs->height_colours[TileHeight(tile)], &_smallmap_contours_andor[t]);
440 * Return the colour a tile would be displayed with in the small map in mode "Vehicles".
442 * @param tile The tile of which we would like to get the colour.
443 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
444 * @return The colour of tile in the small map in mode "Vehicles"
446 static inline uint32_t GetSmallMapVehiclesPixels(TileIndex, TileType t)
448 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
449 return ApplyMask(cs->default_colour, &_smallmap_vehicles_andor[t]);
453 * Return the colour a tile would be displayed with in the small map in mode "Industries".
455 * @param tile The tile of which we would like to get the colour.
456 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
457 * @return The colour of tile in the small map in mode "Industries"
459 static inline uint32_t GetSmallMapIndustriesPixels(TileIndex tile, TileType t)
461 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
462 return ApplyMask(_smallmap_show_heightmap ? cs->height_colours[TileHeight(tile)] : cs->default_colour, &_smallmap_vehicles_andor[t]);
466 * Return the colour a tile would be displayed with in the small map in mode "Routes".
468 * @param tile The tile of which we would like to get the colour.
469 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
470 * @return The colour of tile in the small map in mode "Routes"
472 static inline uint32_t GetSmallMapRoutesPixels(TileIndex tile, TileType t)
474 switch (t) {
475 case MP_STATION:
476 switch (GetStationType(tile)) {
477 case STATION_RAIL: return MKCOLOUR_XXXX(PC_VERY_DARK_BROWN);
478 case STATION_AIRPORT: return MKCOLOUR_XXXX(PC_RED);
479 case STATION_TRUCK: return MKCOLOUR_XXXX(PC_ORANGE);
480 case STATION_BUS: return MKCOLOUR_XXXX(PC_YELLOW);
481 case STATION_DOCK: return MKCOLOUR_XXXX(PC_LIGHT_BLUE);
482 default: return MKCOLOUR_FFFF;
485 case MP_RAILWAY: {
486 AndOr andor = {
487 MKCOLOUR_0XX0(GetRailTypeInfo(GetRailType(tile))->map_colour),
488 _smallmap_contours_andor[t].mand
491 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
492 return ApplyMask(cs->default_colour, &andor);
495 case MP_ROAD: {
496 const RoadTypeInfo *rti = nullptr;
497 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
498 rti = GetRoadTypeInfo(GetRoadTypeRoad(tile));
499 } else {
500 rti = GetRoadTypeInfo(GetRoadTypeTram(tile));
502 if (rti != nullptr) {
503 AndOr andor = {
504 MKCOLOUR_0XX0(rti->map_colour),
505 _smallmap_contours_andor[t].mand
508 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
509 return ApplyMask(cs->default_colour, &andor);
511 [[fallthrough]];
514 default:
515 /* Ground colour */
516 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
517 return ApplyMask(cs->default_colour, &_smallmap_contours_andor[t]);
522 * Return the colour a tile would be displayed with in the small map in mode "link stats".
524 * @param tile The tile of which we would like to get the colour.
525 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
526 * @return The colour of tile in the small map in mode "link stats"
528 static inline uint32_t GetSmallMapLinkStatsPixels(TileIndex tile, TileType t)
530 return _smallmap_show_heightmap ? GetSmallMapContoursPixels(tile, t) : GetSmallMapRoutesPixels(tile, t);
533 static const uint32_t _vegetation_clear_bits[] = {
534 MKCOLOUR_XXXX(PC_GRASS_LAND), ///< full grass
535 MKCOLOUR_XXXX(PC_ROUGH_LAND), ///< rough land
536 MKCOLOUR_XXXX(PC_GREY), ///< rocks
537 MKCOLOUR_XXXX(PC_FIELDS), ///< fields
538 MKCOLOUR_XXXX(PC_LIGHT_BLUE), ///< snow
539 MKCOLOUR_XXXX(PC_ORANGE), ///< desert
540 MKCOLOUR_XXXX(PC_GRASS_LAND), ///< unused
541 MKCOLOUR_XXXX(PC_GRASS_LAND), ///< unused
545 * Return the colour a tile would be displayed with in the smallmap in mode "Vegetation".
547 * @param tile The tile of which we would like to get the colour.
548 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
549 * @return The colour of tile in the smallmap in mode "Vegetation"
551 static inline uint32_t GetSmallMapVegetationPixels(TileIndex tile, TileType t)
553 switch (t) {
554 case MP_CLEAR:
555 if (IsClearGround(tile, CLEAR_GRASS)) {
556 if (GetClearDensity(tile) < 3) return MKCOLOUR_XXXX(PC_BARE_LAND);
557 if (GetTropicZone(tile) == TROPICZONE_RAINFOREST) return MKCOLOUR_XXXX(PC_RAINFOREST);
559 return _vegetation_clear_bits[GetClearGround(tile)];
561 case MP_INDUSTRY:
562 return IsTileForestIndustry(tile) ? MKCOLOUR_XXXX(PC_GREEN) : MKCOLOUR_XXXX(PC_DARK_RED);
564 case MP_TREES:
565 if (GetTreeGround(tile) == TREE_GROUND_SNOW_DESERT || GetTreeGround(tile) == TREE_GROUND_ROUGH_SNOW) {
566 return (_settings_game.game_creation.landscape == LT_ARCTIC) ? MKCOLOUR_XYYX(PC_LIGHT_BLUE, PC_TREES) : MKCOLOUR_XYYX(PC_ORANGE, PC_TREES);
568 return (GetTropicZone(tile) == TROPICZONE_RAINFOREST) ? MKCOLOUR_XYYX(PC_RAINFOREST, PC_TREES) : MKCOLOUR_XYYX(PC_GRASS_LAND, PC_TREES);
570 default:
571 return ApplyMask(MKCOLOUR_XXXX(PC_GRASS_LAND), &_smallmap_vehicles_andor[t]);
576 * Return the colour a tile would be displayed with in the small map in mode "Owner".
578 * @note If include_heightmap is IH_NEVER, the return value can safely be used as a palette colour (by masking it to a uint8_t)
579 * @param tile The tile of which we would like to get the colour.
580 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
581 * @param include_heightmap Whether to return the heightmap/contour colour of this tile (instead of the default land tile colour)
582 * @return The colour of tile in the small map in mode "Owner"
584 uint32_t GetSmallMapOwnerPixels(TileIndex tile, TileType t, IncludeHeightmap include_heightmap)
586 Owner o;
588 switch (t) {
589 case MP_VOID: return MKCOLOUR_XXXX(PC_BLACK);
590 case MP_INDUSTRY: return MKCOLOUR_XXXX(PC_DARK_GREY);
591 case MP_HOUSE: return MKCOLOUR_XXXX(PC_DARK_RED);
592 default: o = GetTileOwner(tile); break;
593 /* FIXME: For MP_ROAD there are multiple owners.
594 * GetTileOwner returns the rail owner (level crossing) resp. the owner of ROADTYPE_ROAD (normal road),
595 * even if there are no ROADTYPE_ROAD bits on the tile.
599 if ((o < MAX_COMPANIES && !_legend_land_owners[_company_to_list_pos[o]].show_on_map) || o == OWNER_NONE || o == OWNER_WATER) {
600 if (t == MP_WATER) return MKCOLOUR_XXXX(PC_WATER);
601 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
602 return ((include_heightmap == IncludeHeightmap::IfEnabled && _smallmap_show_heightmap) || include_heightmap == IncludeHeightmap::Always)
603 ? cs->height_colours[TileHeight(tile)] : cs->default_colour;
604 } else if (o == OWNER_TOWN) {
605 return MKCOLOUR_XXXX(PC_DARK_RED);
608 return MKCOLOUR_XXXX(_legend_land_owners[_company_to_list_pos[o]].colour);
611 /** Vehicle colours in #SMT_VEHICLES mode. Indexed by #VehicleType. */
612 static const uint8_t _vehicle_type_colours[6] = {
613 PC_RED, PC_YELLOW, PC_LIGHT_BLUE, PC_WHITE, PC_BLACK, PC_RED
616 /** Types of legends in the #WID_SM_LEGEND widget. */
617 enum SmallMapType : uint8_t {
618 SMT_CONTOUR,
619 SMT_VEHICLES,
620 SMT_INDUSTRY,
621 SMT_LINKSTATS,
622 SMT_ROUTES,
623 SMT_VEGETATION,
624 SMT_OWNER,
626 DECLARE_ENUM_AS_ADDABLE(SmallMapType)
628 /** Class managing the smallmap window. */
629 class SmallMapWindow : public Window {
630 protected:
631 /** Available kinds of zoomlevel changes. */
632 enum ZoomLevelChange {
633 ZLC_INITIALIZE, ///< Initialize zoom level.
634 ZLC_ZOOM_OUT, ///< Zoom out.
635 ZLC_ZOOM_IN, ///< Zoom in.
638 static SmallMapType map_type; ///< Currently displayed legends.
639 static bool show_towns; ///< Display town names in the smallmap.
640 static bool show_ind_names; ///< Display industry names in the smallmap.
641 static int map_height_limit; ///< Currently used/cached map height limit.
643 static const uint INDUSTRY_MIN_NUMBER_OF_COLUMNS = 2; ///< Minimal number of columns in the #WID_SM_LEGEND widget for the #SMT_INDUSTRY legend.
645 uint min_number_of_columns; ///< Minimal number of columns in legends.
646 uint min_number_of_fixed_rows; ///< Minimal number of rows in the legends for the fixed layouts only (all except #SMT_INDUSTRY).
647 uint column_width; ///< Width of a column in the #WID_SM_LEGEND widget.
648 uint legend_width; ///< Width of legend 'blob'.
650 int32_t scroll_x; ///< Horizontal world coordinate of the base tile left of the top-left corner of the smallmap display.
651 int32_t scroll_y; ///< Vertical world coordinate of the base tile left of the top-left corner of the smallmap display.
652 int32_t subscroll; ///< Number of pixels (0..3) between the right end of the base tile and the pixel at the top-left corner of the smallmap display.
653 int zoom; ///< Zoom level. Bigger number means more zoom-out (further away).
655 std::unique_ptr<LinkGraphOverlay> overlay;
657 /** Notify the industry chain window to stop sending newly selected industries. */
658 static void BreakIndustryChainLink()
660 InvalidateWindowClassesData(WC_INDUSTRY_CARGOES, NUM_INDUSTRYTYPES);
663 static inline Point SmallmapRemapCoords(int x, int y)
665 Point pt;
666 pt.x = (y - x) * 2;
667 pt.y = y + x;
668 return pt;
672 * Draws vertical part of map indicator
673 * @param x X coord of left/right border of main viewport
674 * @param y Y coord of top border of main viewport
675 * @param y2 Y coord of bottom border of main viewport
677 static inline void DrawVertMapIndicator(int x, int y, int y2)
679 GfxFillRect(x, y, x, y + 3, PC_VERY_LIGHT_YELLOW);
680 GfxFillRect(x, y2 - 3, x, y2, PC_VERY_LIGHT_YELLOW);
684 * Draws horizontal part of map indicator
685 * @param x X coord of left border of main viewport
686 * @param x2 X coord of right border of main viewport
687 * @param y Y coord of top/bottom border of main viewport
689 static inline void DrawHorizMapIndicator(int x, int x2, int y)
691 GfxFillRect(x, y, x + 3, y, PC_VERY_LIGHT_YELLOW);
692 GfxFillRect(x2 - 3, y, x2, y, PC_VERY_LIGHT_YELLOW);
696 * Compute minimal required width of the legends.
697 * @return Minimally needed width for displaying the smallmap legends in pixels.
699 inline uint GetMinLegendWidth() const
701 return WidgetDimensions::scaled.framerect.left + this->min_number_of_columns * this->column_width;
705 * Return number of columns that can be displayed in \a width pixels.
706 * @return Number of columns to display.
708 inline uint GetNumberColumnsLegend(uint width) const
710 return width / this->column_width;
714 * Compute height given a number of columns.
715 * @param num_columns Number of columns.
716 * @return Needed height for displaying the smallmap legends in pixels.
718 inline uint GetLegendHeight(uint num_columns) const
720 return WidgetDimensions::scaled.framerect.Vertical() +
721 this->GetNumberRowsLegend(num_columns) * GetCharacterHeight(FS_SMALL);
725 * Get a bitmask for company links to be displayed. Usually this will be
726 * the _local_company. Spectators get to see all companies' links.
727 * @return Company mask.
729 inline CompanyMask GetOverlayCompanyMask() const
731 return Company::IsValidID(_local_company) ? 1U << _local_company : MAX_UVALUE(CompanyMask);
734 /** Blink the industries (if selected) on a regular interval. */
735 IntervalTimer<TimerWindow> blink_interval = {std::chrono::milliseconds(450), [this](auto) {
736 Blink();
739 /** Update the whole map on a regular interval. */
740 IntervalTimer<TimerWindow> refresh_interval = {std::chrono::milliseconds(930), [this](auto) {
741 ForceRefresh();
745 * Rebuilds the colour indices used for fast access to the smallmap contour colours based on the heightlevel.
747 void RebuildColourIndexIfNecessary()
749 /* Rebuild colour indices if necessary. */
750 if (SmallMapWindow::map_height_limit == _settings_game.construction.map_height_limit) return;
752 for (auto &heightmap_scheme : _heightmap_schemes) {
753 /* The heights go from 0 up to and including maximum. */
754 size_t heights = _settings_game.construction.map_height_limit + 1;
755 heightmap_scheme.height_colours.resize(heights);
757 for (size_t z = 0; z < heights; z++) {
758 size_t access_index = (heightmap_scheme.height_colours_base.size() * z) / heights;
760 /* Choose colour by mapping the range (0..max heightlevel) on the complete colour table. */
761 heightmap_scheme.height_colours[z] = heightmap_scheme.height_colours_base[access_index];
765 SmallMapWindow::map_height_limit = _settings_game.construction.map_height_limit;
766 BuildLandLegend();
770 * Get the number of rows in the legend from the number of columns. Those
771 * are at least min_number_of_fixed_rows and possibly more if there are so
772 * many cargoes, industry types or companies that they won't fit in the
773 * available space.
774 * @param columns Number of columns in the legend.
775 * @return Number of rows needed for everything to fit in.
777 uint GetNumberRowsLegend(uint columns) const
779 /* Reserve one column for link colours */
780 uint num_rows_linkstats = CeilDiv(_smallmap_cargo_count, columns - 1);
781 uint num_rows_others = CeilDiv(std::max(_smallmap_industry_count, _smallmap_company_count), columns);
782 return std::max({this->min_number_of_fixed_rows, num_rows_linkstats, num_rows_others});
786 * Select and toggle a legend item. When CTRL is pressed, disable all other
787 * items in the group defined by begin_legend_item and end_legend_item and
788 * keep the clicked one enabled even if it was already enabled before. If
789 * the other items in the group are all disabled already and CTRL is pressed
790 * enable them instead.
791 * @param click_pos the index of the item being selected
792 * @param legend the legend from which we select
793 * @param end_legend_item index one past the last item in the group to be inverted
794 * @param begin_legend_item index of the first item in the group to be inverted
796 void SelectLegendItem(int click_pos, LegendAndColour *legend, int end_legend_item, int begin_legend_item = 0)
798 if (_ctrl_pressed) {
799 /* Disable all, except the clicked one */
800 bool changes = false;
801 for (int i = begin_legend_item; i != end_legend_item; i++) {
802 bool new_state = (i == click_pos);
803 if (legend[i].show_on_map != new_state) {
804 changes = true;
805 legend[i].show_on_map = new_state;
808 if (!changes) {
809 /* Nothing changed? Then show all (again). */
810 for (int i = begin_legend_item; i != end_legend_item; i++) {
811 legend[i].show_on_map = true;
814 } else {
815 legend[click_pos].show_on_map = !legend[click_pos].show_on_map;
818 if (this->map_type == SMT_INDUSTRY) this->BreakIndustryChainLink();
822 * Select a new map type.
823 * @param map_type New map type.
825 void SwitchMapType(SmallMapType map_type)
827 this->RaiseWidget(WID_SM_CONTOUR + this->map_type);
828 this->map_type = map_type;
829 this->LowerWidget(WID_SM_CONTOUR + this->map_type);
831 this->SetupWidgetData();
833 if (map_type == SMT_LINKSTATS) this->overlay->SetDirty();
834 if (map_type != SMT_INDUSTRY) this->BreakIndustryChainLink();
835 this->ReInit();
839 * Set new #scroll_x, #scroll_y, and #subscroll values after limiting them such that the center
840 * of the smallmap always contains a part of the map.
841 * @param sx Proposed new #scroll_x
842 * @param sy Proposed new #scroll_y
843 * @param sub Proposed new #subscroll
845 void SetNewScroll(int sx, int sy, int sub)
847 const NWidgetBase *wi = this->GetWidget<NWidgetBase>(WID_SM_MAP);
848 Point hv = InverseRemapCoords(wi->current_x * ZOOM_BASE * TILE_SIZE / 2, wi->current_y * ZOOM_BASE * TILE_SIZE / 2);
849 hv.x *= this->zoom;
850 hv.y *= this->zoom;
852 if (sx < -hv.x) {
853 sx = -hv.x;
854 sub = 0;
856 if (sx > (int)(Map::MaxX() * TILE_SIZE) - hv.x) {
857 sx = Map::MaxX() * TILE_SIZE - hv.x;
858 sub = 0;
860 if (sy < -hv.y) {
861 sy = -hv.y;
862 sub = 0;
864 if (sy > (int)(Map::MaxY() * TILE_SIZE) - hv.y) {
865 sy = Map::MaxY() * TILE_SIZE - hv.y;
866 sub = 0;
869 this->scroll_x = sx;
870 this->scroll_y = sy;
871 this->subscroll = sub;
872 if (this->map_type == SMT_LINKSTATS) this->overlay->SetDirty();
876 * Adds map indicators to the smallmap.
878 void DrawMapIndicators() const
880 /* Find main viewport. */
881 const Viewport *vp = GetMainWindow()->viewport;
883 Point upper_left_smallmap_coord = InverseRemapCoords2(vp->virtual_left, vp->virtual_top);
884 Point lower_right_smallmap_coord = InverseRemapCoords2(vp->virtual_left + vp->virtual_width - 1, vp->virtual_top + vp->virtual_height - 1);
886 Point upper_left = this->RemapTile(upper_left_smallmap_coord.x / (int)TILE_SIZE, upper_left_smallmap_coord.y / (int)TILE_SIZE);
887 upper_left.x -= this->subscroll;
889 Point lower_right = this->RemapTile(lower_right_smallmap_coord.x / (int)TILE_SIZE, lower_right_smallmap_coord.y / (int)TILE_SIZE);
890 lower_right.x -= this->subscroll;
892 SmallMapWindow::DrawVertMapIndicator(upper_left.x, upper_left.y, lower_right.y);
893 SmallMapWindow::DrawVertMapIndicator(lower_right.x, upper_left.y, lower_right.y);
895 SmallMapWindow::DrawHorizMapIndicator(upper_left.x, lower_right.x, upper_left.y);
896 SmallMapWindow::DrawHorizMapIndicator(upper_left.x, lower_right.x, lower_right.y);
900 * Draws one column of tiles of the small map in a certain mode onto the screen buffer, skipping the shifted rows in between.
902 * @param dst Pointer to a part of the screen buffer to write to.
903 * @param xc The X coordinate of the first tile in the column.
904 * @param yc The Y coordinate of the first tile in the column
905 * @param pitch Number of pixels to advance in the screen buffer each time a pixel is written.
906 * @param reps Number of lines to draw
907 * @param start_pos Position of first pixel to draw.
908 * @param end_pos Position of last pixel to draw (exclusive).
909 * @param blitter current blitter
910 * @note If pixel position is below \c 0, skip drawing.
912 void DrawSmallMapColumn(void *dst, uint xc, uint yc, int pitch, int reps, int start_pos, int end_pos, Blitter *blitter) const
914 void *dst_ptr_abs_end = blitter->MoveTo(_screen.dst_ptr, 0, _screen.height);
915 uint min_xy = _settings_game.construction.freeform_edges ? 1 : 0;
917 do {
918 /* Check if the tile (xc,yc) is within the map range */
919 if (xc >= Map::MaxX() || yc >= Map::MaxY()) continue;
921 /* Check if the dst pointer points to a pixel inside the screen buffer */
922 if (dst < _screen.dst_ptr) continue;
923 if (dst >= dst_ptr_abs_end) continue;
925 /* Construct tilearea covered by (xc, yc, xc + this->zoom, yc + this->zoom) such that it is within min_xy limits. */
926 TileArea ta;
927 if (min_xy == 1 && (xc == 0 || yc == 0)) {
928 if (this->zoom == 1) continue; // The tile area is empty, don't draw anything.
930 ta = TileArea(TileXY(std::max(min_xy, xc), std::max(min_xy, yc)), this->zoom - (xc == 0), this->zoom - (yc == 0));
931 } else {
932 ta = TileArea(TileXY(xc, yc), this->zoom, this->zoom);
934 ta.ClampToMap(); // Clamp to map boundaries (may contain MP_VOID tiles!).
936 uint32_t val = this->GetTileColours(ta);
937 uint8_t *val8 = (uint8_t *)&val;
938 int idx = std::max(0, -start_pos);
939 for (int pos = std::max(0, start_pos); pos < end_pos; pos++) {
940 blitter->SetPixel(dst, idx, 0, val8[idx]);
941 idx++;
943 /* Switch to next tile in the column */
944 } while (xc += this->zoom, yc += this->zoom, dst = blitter->MoveTo(dst, pitch, 0), --reps != 0);
948 * Adds vehicles to the smallmap.
949 * @param dpi the part of the smallmap to be drawn into
950 * @param blitter current blitter
952 void DrawVehicles(const DrawPixelInfo *dpi, Blitter *blitter) const
954 for (const Vehicle *v : Vehicle::Iterate()) {
955 if (v->type == VEH_EFFECT) continue;
956 if (v->vehstatus & (VS_HIDDEN | VS_UNCLICKABLE)) continue;
958 /* Remap into flat coordinates. */
959 Point pt = this->RemapTile(v->x_pos / (int)TILE_SIZE, v->y_pos / (int)TILE_SIZE);
961 int y = pt.y - dpi->top;
962 if (!IsInsideMM(y, 0, dpi->height)) continue; // y is out of bounds.
964 bool skip = false; // Default is to draw both pixels.
965 int x = pt.x - this->subscroll - 3 - dpi->left; // Offset X coordinate.
966 if (x < 0) {
967 /* if x+1 is 0, that means we're on the very left edge,
968 * and should thus only draw a single pixel */
969 if (++x != 0) continue;
970 skip = true;
971 } else if (x >= dpi->width - 1) {
972 /* Check if we're at the very right edge, and if so draw only a single pixel */
973 if (x != dpi->width - 1) continue;
974 skip = true;
977 /* Calculate pointer to pixel and the colour */
978 uint8_t colour = (this->map_type == SMT_VEHICLES) ? _vehicle_type_colours[v->type] : PC_WHITE;
980 /* And draw either one or two pixels depending on clipping */
981 blitter->SetPixel(dpi->dst_ptr, x, y, colour);
982 if (!skip) blitter->SetPixel(dpi->dst_ptr, x + 1, y, colour);
987 * Adds town names to the smallmap.
988 * @param dpi the part of the smallmap to be drawn into
990 void DrawTowns(const DrawPixelInfo *dpi, const int vertical_padding) const
992 for (const Town *t : Town::Iterate()) {
993 /* Remap the town coordinate */
994 Point pt = this->RemapTile(TileX(t->xy), TileY(t->xy));
995 int x = pt.x - this->subscroll - (t->cache.sign.width_small >> 1);
996 int y = pt.y + vertical_padding;
998 /* Check if the town sign is within bounds */
999 if (x + t->cache.sign.width_small > dpi->left &&
1000 x < dpi->left + dpi->width &&
1001 y + GetCharacterHeight(FS_SMALL) > dpi->top &&
1002 y < dpi->top + dpi->height) {
1003 /* And draw it. */
1004 SetDParam(0, t->index);
1005 DrawString(x, x + t->cache.sign.width_small, y, STR_SMALLMAP_TOWN);
1011 * Adds industry names to the smallmap.
1012 * @param dpi the part of the smallmap to be drawn into
1014 void DrawIndustryNames(const DrawPixelInfo *dpi, const int vertical_padding) const
1016 if (this->map_type != SMT_INDUSTRY) return;
1018 for (const Industry *i : Industry::Iterate()) {
1019 const LegendAndColour &tbl = _legend_from_industries[_industry_to_list_pos[i->type]];
1020 if (!tbl.show_on_map) continue;
1022 /* Industry names blink together with their blobs in the smallmap. */
1023 const bool is_blinking = i->type == _smallmap_industry_highlight && !_smallmap_industry_highlight_state;
1024 if (is_blinking) continue;
1026 if (_industry_to_name_string_width[i->type] == 0) {
1027 _industry_to_name_string_width[i->type] = GetStringBoundingBox(tbl.legend, FS_SMALL).width;
1029 const uint16_t &legend_text_width = _industry_to_name_string_width[i->type];
1031 /* Remap the industry coordinate */
1032 const TileIndex &tile = i->location.GetCenterTile();
1033 const Point pt = this->RemapTile(TileX(tile), TileY(tile));
1034 const int x = pt.x - this->subscroll - (legend_text_width / 2);
1035 const int y = pt.y + vertical_padding;
1037 /* Check if the industry name is within bounds */
1038 if (x + legend_text_width > dpi->left &&
1039 x < dpi->left + dpi->width &&
1040 y + GetCharacterHeight(FS_SMALL) > dpi->top &&
1041 y < dpi->top + dpi->height) {
1043 /* And draw it. */
1044 DrawString(x, x + legend_text_width, y, tbl.legend, TC_WHITE, SA_LEFT, false, FS_SMALL);
1050 * Draws the small map.
1052 * Basically, the small map is draw column of pixels by column of pixels. The pixels
1053 * are drawn directly into the screen buffer. The final map is drawn in multiple passes.
1054 * The passes are:
1055 * <ol><li>The colours of tiles in the different modes.</li>
1056 * <li>Town names (optional)</li></ol>
1058 * @param dpi pointer to pixel to write onto
1060 void DrawSmallMap(DrawPixelInfo *dpi) const
1062 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
1063 AutoRestoreBackup dpi_backup(_cur_dpi, dpi);
1065 /* Clear it */
1066 GfxFillRect(dpi->left, dpi->top, dpi->left + dpi->width - 1, dpi->top + dpi->height - 1, PC_BLACK);
1068 /* Which tile is displayed at (dpi->left, dpi->top)? */
1069 int dx;
1070 Point tile = this->PixelToTile(dpi->left, dpi->top, &dx);
1071 int tile_x = this->scroll_x / (int)TILE_SIZE + tile.x;
1072 int tile_y = this->scroll_y / (int)TILE_SIZE + tile.y;
1074 void *ptr = blitter->MoveTo(dpi->dst_ptr, -dx - 4, 0);
1075 int x = - dx - 4;
1076 int y = 0;
1078 for (;;) {
1079 /* Distance from left edge */
1080 if (x >= -3) {
1081 if (x >= dpi->width) break; // Exit the loop.
1083 int end_pos = std::min(dpi->width, x + 4);
1084 int reps = (dpi->height - y + 1) / 2; // Number of lines.
1085 if (reps > 0) {
1086 this->DrawSmallMapColumn(ptr, tile_x, tile_y, dpi->pitch * 2, reps, x, end_pos, blitter);
1090 if (y == 0) {
1091 tile_y += this->zoom;
1092 y++;
1093 ptr = blitter->MoveTo(ptr, 0, 1);
1094 } else {
1095 tile_x -= this->zoom;
1096 y--;
1097 ptr = blitter->MoveTo(ptr, 0, -1);
1099 ptr = blitter->MoveTo(ptr, 2, 0);
1100 x += 2;
1103 /* Draw vehicles */
1104 if (this->map_type == SMT_CONTOUR || this->map_type == SMT_VEHICLES) this->DrawVehicles(dpi, blitter);
1106 /* Draw link stat overlay */
1107 if (this->map_type == SMT_LINKSTATS) this->overlay->Draw(dpi);
1109 const int map_labels_vertical_padding = ScaleGUITrad(2);
1111 /* Draw town names */
1112 if (this->show_towns) this->DrawTowns(dpi, map_labels_vertical_padding);
1114 /* Draw industry names */
1115 if (this->show_ind_names) this->DrawIndustryNames(dpi, map_labels_vertical_padding);
1117 /* Draw map indicators */
1118 this->DrawMapIndicators();
1122 * Remap tile to location on this smallmap.
1123 * @param tile_x X coordinate of the tile.
1124 * @param tile_y Y coordinate of the tile.
1125 * @return Position to draw on.
1127 Point RemapTile(int tile_x, int tile_y) const
1129 int x_offset = tile_x - this->scroll_x / (int)TILE_SIZE;
1130 int y_offset = tile_y - this->scroll_y / (int)TILE_SIZE;
1132 if (this->zoom == 1) return SmallmapRemapCoords(x_offset, y_offset);
1134 /* For negative offsets, round towards -inf. */
1135 if (x_offset < 0) x_offset -= this->zoom - 1;
1136 if (y_offset < 0) y_offset -= this->zoom - 1;
1138 return SmallmapRemapCoords(x_offset / this->zoom, y_offset / this->zoom);
1142 * Determine the tile relative to the base tile of the smallmap, and the pixel position at
1143 * that tile for a point in the smallmap.
1144 * @param px Horizontal coordinate of the pixel.
1145 * @param py Vertical coordinate of the pixel.
1146 * @param[out] sub Pixel position at the tile (0..3).
1147 * @param add_sub Add current #subscroll to the position.
1148 * @return Tile being displayed at the given position relative to #scroll_x and #scroll_y.
1149 * @note The #subscroll offset is already accounted for.
1151 Point PixelToTile(int px, int py, int *sub, bool add_sub = true) const
1153 if (add_sub) px += this->subscroll; // Total horizontal offset.
1155 /* For each two rows down, add a x and a y tile, and
1156 * For each four pixels to the right, move a tile to the right. */
1157 Point pt = {((py >> 1) - (px >> 2)) * this->zoom, ((py >> 1) + (px >> 2)) * this->zoom};
1158 px &= 3;
1160 if (py & 1) { // Odd number of rows, handle the 2 pixel shift.
1161 if (px < 2) {
1162 pt.x += this->zoom;
1163 px += 2;
1164 } else {
1165 pt.y += this->zoom;
1166 px -= 2;
1170 *sub = px;
1171 return pt;
1175 * Compute base parameters of the smallmap such that tile (\a tx, \a ty) starts at pixel (\a x, \a y).
1176 * @param tx Tile x coordinate.
1177 * @param ty Tile y coordinate.
1178 * @param x Non-negative horizontal position in the display where the tile starts.
1179 * @param y Non-negative vertical position in the display where the tile starts.
1180 * @param[out] sub Value of #subscroll needed.
1181 * @return #scroll_x, #scroll_y values.
1183 Point ComputeScroll(int tx, int ty, int x, int y, int *sub) const
1185 assert(x >= 0 && y >= 0);
1187 int new_sub;
1188 Point tile_xy = PixelToTile(x, y, &new_sub, false);
1189 tx -= tile_xy.x;
1190 ty -= tile_xy.y;
1192 Point scroll;
1193 if (new_sub == 0) {
1194 *sub = 0;
1195 scroll.x = (tx + this->zoom) * TILE_SIZE;
1196 scroll.y = (ty - this->zoom) * TILE_SIZE;
1197 } else {
1198 *sub = 4 - new_sub;
1199 scroll.x = (tx + 2 * this->zoom) * TILE_SIZE;
1200 scroll.y = (ty - 2 * this->zoom) * TILE_SIZE;
1202 return scroll;
1206 * Initialize or change the zoom level.
1207 * @param change Way to change the zoom level.
1208 * @param zoom_pt Position to keep fixed while zooming.
1209 * @pre \c *zoom_pt should contain a point in the smallmap display when zooming in or out.
1211 void SetZoomLevel(ZoomLevelChange change, const Point *zoom_pt)
1213 static const int zoomlevels[] = {1, 2, 4, 6, 8}; // Available zoom levels. Bigger number means more zoom-out (further away).
1214 static const int MIN_ZOOM_INDEX = 0;
1215 static const int MAX_ZOOM_INDEX = lengthof(zoomlevels) - 1;
1217 int new_index, cur_index, sub;
1218 Point tile;
1219 switch (change) {
1220 case ZLC_INITIALIZE:
1221 cur_index = - 1; // Definitely different from new_index.
1222 new_index = MIN_ZOOM_INDEX;
1223 tile.x = tile.y = 0;
1224 break;
1226 case ZLC_ZOOM_IN:
1227 case ZLC_ZOOM_OUT:
1228 for (cur_index = MIN_ZOOM_INDEX; cur_index <= MAX_ZOOM_INDEX; cur_index++) {
1229 if (this->zoom == zoomlevels[cur_index]) break;
1231 assert(cur_index <= MAX_ZOOM_INDEX);
1233 tile = this->PixelToTile(zoom_pt->x, zoom_pt->y, &sub);
1234 new_index = Clamp(cur_index + ((change == ZLC_ZOOM_IN) ? -1 : 1), MIN_ZOOM_INDEX, MAX_ZOOM_INDEX);
1235 break;
1237 default: NOT_REACHED();
1240 if (new_index != cur_index) {
1241 this->zoom = zoomlevels[new_index];
1242 if (cur_index >= 0) {
1243 Point new_tile = this->PixelToTile(zoom_pt->x, zoom_pt->y, &sub);
1244 this->SetNewScroll(this->scroll_x + (tile.x - new_tile.x) * TILE_SIZE,
1245 this->scroll_y + (tile.y - new_tile.y) * TILE_SIZE, sub);
1246 } else if (this->map_type == SMT_LINKSTATS) {
1247 this->overlay->SetDirty();
1249 this->SetWidgetDisabledState(WID_SM_ZOOM_IN, this->zoom == zoomlevels[MIN_ZOOM_INDEX]);
1250 this->SetWidgetDisabledState(WID_SM_ZOOM_OUT, this->zoom == zoomlevels[MAX_ZOOM_INDEX]);
1251 this->SetDirty();
1256 * Set the link graph overlay cargo mask from the legend.
1258 void SetOverlayCargoMask()
1260 CargoTypes cargo_mask = 0;
1261 for (int i = 0; i != _smallmap_cargo_count; ++i) {
1262 if (_legend_linkstats[i].show_on_map) SetBit(cargo_mask, _legend_linkstats[i].type);
1264 this->overlay->SetCargoMask(cargo_mask);
1268 * Function to set up widgets depending on the information being shown on the smallmap.
1270 void SetupWidgetData()
1272 StringID legend_tooltip;
1273 StringID enable_all_tooltip;
1274 StringID disable_all_tooltip;
1275 int industry_names_select_plane;
1276 int select_buttons_plane;
1277 switch (this->map_type) {
1278 case SMT_INDUSTRY:
1279 legend_tooltip = STR_SMALLMAP_TOOLTIP_INDUSTRY_SELECTION;
1280 enable_all_tooltip = STR_SMALLMAP_TOOLTIP_ENABLE_ALL_INDUSTRIES;
1281 disable_all_tooltip = STR_SMALLMAP_TOOLTIP_DISABLE_ALL_INDUSTRIES;
1282 industry_names_select_plane = 0;
1283 select_buttons_plane = 0;
1284 break;
1286 case SMT_OWNER:
1287 legend_tooltip = STR_SMALLMAP_TOOLTIP_COMPANY_SELECTION;
1288 enable_all_tooltip = STR_SMALLMAP_TOOLTIP_ENABLE_ALL_COMPANIES;
1289 disable_all_tooltip = STR_SMALLMAP_TOOLTIP_DISABLE_ALL_COMPANIES;
1290 industry_names_select_plane = SZSP_NONE;
1291 select_buttons_plane = 0;
1292 break;
1294 case SMT_LINKSTATS:
1295 legend_tooltip = STR_SMALLMAP_TOOLTIP_CARGO_SELECTION;
1296 enable_all_tooltip = STR_SMALLMAP_TOOLTIP_ENABLE_ALL_CARGOS;
1297 disable_all_tooltip = STR_SMALLMAP_TOOLTIP_DISABLE_ALL_CARGOS;
1298 industry_names_select_plane = SZSP_NONE;
1299 select_buttons_plane = 0;
1300 break;
1302 default:
1303 legend_tooltip = STR_NULL;
1304 enable_all_tooltip = STR_NULL;
1305 disable_all_tooltip = STR_NULL;
1306 industry_names_select_plane = SZSP_NONE;
1307 select_buttons_plane = 1;
1308 break;
1311 this->GetWidget<NWidgetCore>(WID_SM_LEGEND)->SetDataTip(STR_NULL, legend_tooltip);
1312 this->GetWidget<NWidgetCore>(WID_SM_ENABLE_ALL)->SetDataTip(STR_SMALLMAP_ENABLE_ALL, enable_all_tooltip);
1313 this->GetWidget<NWidgetCore>(WID_SM_DISABLE_ALL)->SetDataTip(STR_SMALLMAP_DISABLE_ALL, disable_all_tooltip);
1314 this->GetWidget<NWidgetStacked>(WID_SM_SHOW_IND_NAMES_SEL)->SetDisplayedPlane(industry_names_select_plane);
1315 this->GetWidget<NWidgetStacked>(WID_SM_SELECT_BUTTONS)->SetDisplayedPlane(select_buttons_plane);
1319 * Decide which colours to show to the user for a group of tiles.
1320 * @param ta Tile area to investigate.
1321 * @return Colours to display.
1323 uint32_t GetTileColours(const TileArea &ta) const
1325 int importance = 0;
1326 TileIndex tile = INVALID_TILE; // Position of the most important tile.
1327 TileType et = MP_VOID; // Effective tile type at that position.
1329 for (TileIndex ti : ta) {
1330 TileType ttype = GetTileType(ti);
1332 switch (ttype) {
1333 case MP_TUNNELBRIDGE: {
1334 TransportType tt = GetTunnelBridgeTransportType(ti);
1336 switch (tt) {
1337 case TRANSPORT_RAIL: ttype = MP_RAILWAY; break;
1338 case TRANSPORT_ROAD: ttype = MP_ROAD; break;
1339 default: ttype = MP_WATER; break;
1341 break;
1344 case MP_INDUSTRY:
1345 /* Special handling of industries while in "Industries" smallmap view. */
1346 if (this->map_type == SMT_INDUSTRY) {
1347 /* If industry is allowed to be seen, use its colour on the map.
1348 * This has the highest priority above any value in _tiletype_importance. */
1349 IndustryType type = Industry::GetByTile(ti)->type;
1350 if (_legend_from_industries[_industry_to_list_pos[type]].show_on_map) {
1351 if (type == _smallmap_industry_highlight) {
1352 if (_smallmap_industry_highlight_state) return MKCOLOUR_XXXX(PC_WHITE);
1353 } else {
1354 return GetIndustrySpec(type)->map_colour * 0x01010101;
1357 /* Otherwise make it disappear */
1358 ttype = IsTileOnWater(ti) ? MP_WATER : MP_CLEAR;
1360 break;
1362 default:
1363 break;
1366 if (_tiletype_importance[ttype] > importance) {
1367 importance = _tiletype_importance[ttype];
1368 tile = ti;
1369 et = ttype;
1373 switch (this->map_type) {
1374 case SMT_CONTOUR:
1375 return GetSmallMapContoursPixels(tile, et);
1377 case SMT_VEHICLES:
1378 return GetSmallMapVehiclesPixels(tile, et);
1380 case SMT_INDUSTRY:
1381 return GetSmallMapIndustriesPixels(tile, et);
1383 case SMT_LINKSTATS:
1384 return GetSmallMapLinkStatsPixels(tile, et);
1386 case SMT_ROUTES:
1387 return GetSmallMapRoutesPixels(tile, et);
1389 case SMT_VEGETATION:
1390 return GetSmallMapVegetationPixels(tile, et);
1392 case SMT_OWNER:
1393 return GetSmallMapOwnerPixels(tile, et, IncludeHeightmap::IfEnabled);
1395 default: NOT_REACHED();
1400 * Determines the mouse position on the legend.
1401 * @param pt Mouse position.
1402 * @return Legend item under the mouse.
1404 int GetPositionOnLegend(Point pt)
1406 const NWidgetBase *wi = this->GetWidget<NWidgetBase>(WID_SM_LEGEND);
1407 uint line = (pt.y - wi->pos_y - WidgetDimensions::scaled.framerect.top) / GetCharacterHeight(FS_SMALL);
1408 uint columns = this->GetNumberColumnsLegend(wi->current_x);
1409 uint number_of_rows = this->GetNumberRowsLegend(columns);
1410 if (line >= number_of_rows) return -1;
1412 bool rtl = _current_text_dir == TD_RTL;
1413 int x = pt.x - wi->pos_x;
1414 if (rtl) x = wi->current_x - x;
1415 uint column = (x - WidgetDimensions::scaled.framerect.left) / this->column_width;
1417 return (column * number_of_rows) + line;
1420 /** Update all the links on the map. */
1421 void UpdateLinks()
1423 if (this->map_type == SMT_LINKSTATS) {
1424 CompanyMask company_mask = this->GetOverlayCompanyMask();
1425 if (this->overlay->GetCompanyMask() != company_mask) {
1426 this->overlay->SetCompanyMask(company_mask);
1427 } else {
1428 this->overlay->SetDirty();
1433 /** Blink the industries (if hover over an industry). */
1434 void Blink()
1436 if (_smallmap_industry_highlight == INVALID_INDUSTRYTYPE) return;
1438 _smallmap_industry_highlight_state = !_smallmap_industry_highlight_state;
1440 this->UpdateLinks();
1441 this->SetDirty();
1444 /** Force a full refresh of the map. */
1445 void ForceRefresh()
1447 if (_smallmap_industry_highlight != INVALID_INDUSTRYTYPE) return;
1449 this->UpdateLinks();
1450 this->SetDirty();
1453 public:
1454 friend class NWidgetSmallmapDisplay;
1456 SmallMapWindow(WindowDesc &desc, int window_number) : Window(desc)
1458 _smallmap_industry_highlight = INVALID_INDUSTRYTYPE;
1459 this->overlay = std::make_unique<LinkGraphOverlay>(this, WID_SM_MAP, 0, this->GetOverlayCompanyMask(), 1);
1460 this->CreateNestedTree();
1461 this->LowerWidget(WID_SM_CONTOUR + this->map_type);
1463 this->RebuildColourIndexIfNecessary();
1465 this->SetWidgetLoweredState(WID_SM_SHOW_HEIGHT, _smallmap_show_heightmap);
1467 this->SetWidgetLoweredState(WID_SM_TOGGLETOWNNAME, this->show_towns);
1468 this->SetWidgetLoweredState(WID_SM_SHOW_IND_NAMES, this->show_ind_names);
1470 this->SetupWidgetData();
1471 this->FinishInitNested(window_number);
1473 this->SetZoomLevel(ZLC_INITIALIZE, nullptr);
1474 this->SmallMapCenterOnCurrentPos();
1475 this->SetOverlayCargoMask();
1479 * Center the small map on the current center of the viewport.
1481 void SmallMapCenterOnCurrentPos()
1483 const Viewport *vp = GetMainWindow()->viewport;
1484 Point viewport_center = InverseRemapCoords2(vp->virtual_left + vp->virtual_width / 2, vp->virtual_top + vp->virtual_height / 2);
1486 int sub;
1487 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SM_MAP);
1488 Point sxy = this->ComputeScroll(viewport_center.x / (int)TILE_SIZE, viewport_center.y / (int)TILE_SIZE,
1489 std::max(0, (int)wid->current_x / 2 - 2), wid->current_y / 2, &sub);
1490 this->SetNewScroll(sxy.x, sxy.y, sub);
1491 this->SetDirty();
1495 * Get the center of the given station as point on the screen in the smallmap window.
1496 * @param st Station to find in the smallmap.
1497 * @return Point with coordinates of the station.
1499 Point GetStationMiddle(const Station *st) const
1501 int x = CenterBounds(st->rect.left, st->rect.right, 0);
1502 int y = CenterBounds(st->rect.top, st->rect.bottom, 0);
1503 Point ret = this->RemapTile(x, y);
1505 /* Same magic 3 as in DrawVehicles; that's where I got it from.
1506 * No idea what it is, but without it the result looks bad.
1508 ret.x -= 3 + this->subscroll;
1509 return ret;
1512 void Close([[maybe_unused]] int data) override
1514 this->BreakIndustryChainLink();
1515 this->Window::Close();
1518 void SetStringParameters(WidgetID widget) const override
1520 switch (widget) {
1521 case WID_SM_CAPTION:
1522 SetDParam(0, STR_SMALLMAP_TYPE_CONTOURS + this->map_type);
1523 break;
1527 void OnInit() override
1529 uint min_width = 0;
1530 this->min_number_of_columns = INDUSTRY_MIN_NUMBER_OF_COLUMNS;
1531 this->min_number_of_fixed_rows = lengthof(_linkstat_colours_in_legenda);
1532 for (uint i = 0; i < lengthof(_legend_table); i++) {
1533 uint height = 0;
1534 uint num_columns = 1;
1535 for (const LegendAndColour *tbl = _legend_table[i]; !tbl->end; ++tbl) {
1536 StringID str;
1537 if (i == SMT_INDUSTRY) {
1538 SetDParam(0, tbl->legend);
1539 SetDParam(1, IndustryPool::MAX_SIZE);
1540 str = STR_SMALLMAP_INDUSTRY;
1541 } else if (i == SMT_LINKSTATS) {
1542 SetDParam(0, tbl->legend);
1543 str = STR_SMALLMAP_LINKSTATS;
1544 } else if (i == SMT_OWNER) {
1545 if (tbl->company != INVALID_COMPANY) {
1546 if (!Company::IsValidID(tbl->company)) {
1547 /* Rebuild the owner legend. */
1548 BuildOwnerLegend();
1549 this->OnInit();
1550 return;
1552 /* Non-fixed legend entries for the owner view. */
1553 SetDParam(0, tbl->company);
1554 str = STR_SMALLMAP_COMPANY;
1555 } else {
1556 str = tbl->legend;
1558 } else {
1559 if (tbl->col_break) {
1560 this->min_number_of_fixed_rows = std::max(this->min_number_of_fixed_rows, height);
1561 height = 0;
1562 num_columns++;
1564 height++;
1565 str = tbl->legend;
1567 min_width = std::max(GetStringBoundingBox(str).width, min_width);
1569 this->min_number_of_fixed_rows = std::max(this->min_number_of_fixed_rows, height);
1570 this->min_number_of_columns = std::max(this->min_number_of_columns, num_columns);
1573 /* Width of the legend blob. */
1574 this->legend_width = GetCharacterHeight(FS_SMALL) * 9 / 6;
1576 /* The width of a column is the minimum width of all texts + the size of the blob + some spacing */
1577 this->column_width = min_width + WidgetDimensions::scaled.hsep_normal + this->legend_width + WidgetDimensions::scaled.framerect.Horizontal();
1579 /* Cached string widths of industry names in the smallmap. Calculation is deferred to DrawIndustryNames(). */
1580 std::fill(std::begin(_industry_to_name_string_width), std::end(_industry_to_name_string_width), 0);
1583 void OnPaint() override
1585 if (this->map_type == SMT_OWNER) {
1586 for (const LegendAndColour *tbl = _legend_table[this->map_type]; !tbl->end; ++tbl) {
1587 if (tbl->company != INVALID_COMPANY && !Company::IsValidID(tbl->company)) {
1588 /* Rebuild the owner legend. */
1589 BuildOwnerLegend();
1590 this->InvalidateData(1);
1591 break;
1596 this->DrawWidgets();
1599 void DrawWidget(const Rect &r, WidgetID widget) const override
1601 switch (widget) {
1602 case WID_SM_MAP: {
1603 Rect ir = r.Shrink(WidgetDimensions::scaled.bevel);
1604 DrawPixelInfo new_dpi;
1605 if (!FillDrawPixelInfo(&new_dpi, ir)) return;
1606 this->DrawSmallMap(&new_dpi);
1607 break;
1610 case WID_SM_LEGEND: {
1611 uint columns = this->GetNumberColumnsLegend(r.Width());
1612 uint number_of_rows = this->GetNumberRowsLegend(columns);
1613 bool rtl = _current_text_dir == TD_RTL;
1614 uint i = 0; // Row counter for industry legend.
1615 uint row_height = GetCharacterHeight(FS_SMALL);
1616 int padding = ScaleGUITrad(1);
1618 Rect origin = r.WithWidth(this->column_width, rtl).Shrink(WidgetDimensions::scaled.framerect).WithHeight(row_height);
1619 Rect text = origin.Indent(this->legend_width + WidgetDimensions::scaled.hsep_normal, rtl);
1620 Rect icon = origin.WithWidth(this->legend_width, rtl).Shrink(0, padding, 0, 0);
1622 StringID string = STR_NULL;
1623 switch (this->map_type) {
1624 case SMT_INDUSTRY:
1625 string = STR_SMALLMAP_INDUSTRY;
1626 break;
1627 case SMT_LINKSTATS:
1628 string = STR_SMALLMAP_LINKSTATS;
1629 break;
1630 case SMT_OWNER:
1631 string = STR_SMALLMAP_COMPANY;
1632 break;
1633 default:
1634 break;
1637 for (const LegendAndColour *tbl = _legend_table[this->map_type]; !tbl->end; ++tbl) {
1638 if (tbl->col_break || ((this->map_type == SMT_INDUSTRY || this->map_type == SMT_OWNER || this->map_type == SMT_LINKSTATS) && i++ >= number_of_rows)) {
1639 /* Column break needed, continue at top, COLUMN_WIDTH pixels
1640 * (one "row") to the right. */
1641 int x = rtl ? -(int)this->column_width : this->column_width;
1642 int y = origin.top - text.top;
1643 text = text.Translate(x, y);
1644 icon = icon.Translate(x, y);
1645 i = 1;
1648 uint8_t legend_colour = tbl->colour;
1650 switch (this->map_type) {
1651 case SMT_INDUSTRY:
1652 /* Industry name must be formatted, since it's not in tiny font in the specs.
1653 * So, draw with a parameter and use the STR_SMALLMAP_INDUSTRY string, which is tiny font */
1654 SetDParam(0, tbl->legend);
1655 SetDParam(1, Industry::GetIndustryTypeCount(tbl->type));
1656 if (tbl->show_on_map && tbl->type == _smallmap_industry_highlight) {
1657 legend_colour = _smallmap_industry_highlight_state ? PC_WHITE : PC_BLACK;
1659 [[fallthrough]];
1661 case SMT_LINKSTATS:
1662 SetDParam(0, tbl->legend);
1663 [[fallthrough]];
1665 case SMT_OWNER:
1666 if (this->map_type != SMT_OWNER || tbl->company != INVALID_COMPANY) {
1667 if (this->map_type == SMT_OWNER) SetDParam(0, tbl->company);
1668 if (!tbl->show_on_map) {
1669 /* Simply draw the string, not the black border of the legend colour.
1670 * This will enforce the idea of the disabled item */
1671 DrawString(text, string, TC_GREY);
1672 } else {
1673 DrawString(text, string, TC_BLACK);
1674 GfxFillRect(icon, PC_BLACK); // Outer border of the legend colour
1676 break;
1678 [[fallthrough]];
1680 default:
1681 if (this->map_type == SMT_CONTOUR) SetDParam(0, tbl->height * TILE_HEIGHT_STEP);
1682 /* Anything that is not an industry or a company is using normal process */
1683 GfxFillRect(icon, PC_BLACK);
1684 DrawString(text, tbl->legend);
1685 break;
1687 GfxFillRect(icon.Shrink(WidgetDimensions::scaled.bevel), legend_colour); // Legend colour
1689 text = text.Translate(0, row_height);
1690 icon = icon.Translate(0, row_height);
1696 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1698 switch (widget) {
1699 case WID_SM_MAP: { // Map window
1700 if (click_count > 0) this->mouse_capture_widget = widget;
1702 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SM_MAP);
1703 Window *w = GetMainWindow();
1704 int sub;
1705 pt = this->PixelToTile(pt.x - wid->pos_x, pt.y - wid->pos_y, &sub);
1706 ScrollWindowTo(this->scroll_x + pt.x * TILE_SIZE, this->scroll_y + pt.y * TILE_SIZE, -1, w);
1708 this->SetDirty();
1709 break;
1712 case WID_SM_ZOOM_IN:
1713 case WID_SM_ZOOM_OUT: {
1714 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SM_MAP);
1715 Point zoom_pt = { (int)wid->current_x / 2, (int)wid->current_y / 2};
1716 this->SetZoomLevel((widget == WID_SM_ZOOM_IN) ? ZLC_ZOOM_IN : ZLC_ZOOM_OUT, &zoom_pt);
1717 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
1718 break;
1721 case WID_SM_CONTOUR: // Show land contours
1722 case WID_SM_VEHICLES: // Show vehicles
1723 case WID_SM_INDUSTRIES: // Show industries
1724 case WID_SM_LINKSTATS: // Show route map
1725 case WID_SM_ROUTES: // Show transport routes
1726 case WID_SM_VEGETATION: // Show vegetation
1727 case WID_SM_OWNERS: // Show land owners
1728 this->SwitchMapType((SmallMapType)(widget - WID_SM_CONTOUR));
1729 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
1730 break;
1732 case WID_SM_CENTERMAP: // Center the smallmap again
1733 this->SmallMapCenterOnCurrentPos();
1734 this->HandleButtonClick(WID_SM_CENTERMAP);
1735 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
1736 break;
1738 case WID_SM_TOGGLETOWNNAME: // Toggle town names
1739 this->show_towns = !this->show_towns;
1740 this->SetWidgetLoweredState(WID_SM_TOGGLETOWNNAME, this->show_towns);
1742 this->SetDirty();
1743 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
1744 break;
1746 case WID_SM_SHOW_IND_NAMES: // Toggle industry names
1747 this->show_ind_names = !this->show_ind_names;
1748 this->SetWidgetLoweredState(WID_SM_SHOW_IND_NAMES, this->show_ind_names);
1750 this->SetDirty();
1751 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
1752 break;
1754 case WID_SM_LEGEND: // Legend
1755 if (this->map_type == SMT_INDUSTRY || this->map_type == SMT_LINKSTATS || this->map_type == SMT_OWNER) {
1756 int click_pos = this->GetPositionOnLegend(pt);
1757 if (click_pos < 0) break;
1759 /* If industry type small map*/
1760 if (this->map_type == SMT_INDUSTRY) {
1761 /* If click on industries label, find right industry type and enable/disable it. */
1762 if (click_pos < _smallmap_industry_count) {
1763 this->SelectLegendItem(click_pos, _legend_from_industries, _smallmap_industry_count);
1765 } else if (this->map_type == SMT_LINKSTATS) {
1766 if (click_pos < _smallmap_cargo_count) {
1767 this->SelectLegendItem(click_pos, _legend_linkstats, _smallmap_cargo_count);
1768 this->SetOverlayCargoMask();
1770 } else if (this->map_type == SMT_OWNER) {
1771 if (click_pos < _smallmap_company_count) {
1772 this->SelectLegendItem(click_pos, _legend_land_owners, _smallmap_company_count, NUM_NO_COMPANY_ENTRIES);
1775 this->SetDirty();
1777 break;
1779 case WID_SM_ENABLE_ALL:
1780 case WID_SM_DISABLE_ALL: {
1781 LegendAndColour *tbl = nullptr;
1782 switch (this->map_type) {
1783 case SMT_INDUSTRY:
1784 tbl = _legend_from_industries;
1785 this->BreakIndustryChainLink();
1786 break;
1787 case SMT_OWNER:
1788 tbl = &(_legend_land_owners[NUM_NO_COMPANY_ENTRIES]);
1789 break;
1790 case SMT_LINKSTATS:
1791 tbl = _legend_linkstats;
1792 break;
1793 default:
1794 NOT_REACHED();
1796 for (;!tbl->end && tbl->legend != STR_LINKGRAPH_LEGEND_UNUSED; ++tbl) {
1797 tbl->show_on_map = (widget == WID_SM_ENABLE_ALL);
1799 if (this->map_type == SMT_LINKSTATS) this->SetOverlayCargoMask();
1800 this->SetDirty();
1801 break;
1804 case WID_SM_SHOW_HEIGHT: // Enable/disable showing of heightmap.
1805 _smallmap_show_heightmap = !_smallmap_show_heightmap;
1806 this->SetWidgetLoweredState(WID_SM_SHOW_HEIGHT, _smallmap_show_heightmap);
1807 this->SetDirty();
1808 break;
1813 * Some data on this window has become invalid.
1814 * @param data Information about the changed data.
1815 * - data = 0: Displayed industries at the industry chain window have changed.
1816 * - data = 1: Companies have changed.
1817 * - data = 2: Cheat changing the maximum heightlevel has been used, rebuild our heightlevel-to-colour index
1818 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1820 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1822 if (!gui_scope) return;
1824 switch (data) {
1825 case 1:
1826 /* The owner legend has already been rebuilt. */
1827 this->ReInit();
1828 break;
1830 case 0: {
1831 extern std::bitset<NUM_INDUSTRYTYPES> _displayed_industries;
1832 if (this->map_type != SMT_INDUSTRY) this->SwitchMapType(SMT_INDUSTRY);
1834 for (int i = 0; i != _smallmap_industry_count; i++) {
1835 _legend_from_industries[i].show_on_map = _displayed_industries.test(_legend_from_industries[i].type);
1837 break;
1840 case 2:
1841 this->RebuildColourIndexIfNecessary();
1842 break;
1844 default: NOT_REACHED();
1846 this->SetDirty();
1849 bool OnRightClick(Point, WidgetID widget) override
1851 if (widget != WID_SM_MAP || _scrolling_viewport) return false;
1853 _scrolling_viewport = true;
1854 return true;
1857 void OnMouseWheel(int wheel) override
1859 if (_settings_client.gui.scrollwheel_scrolling != SWS_OFF) {
1860 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SM_MAP);
1861 int cursor_x = _cursor.pos.x - this->left - wid->pos_x;
1862 int cursor_y = _cursor.pos.y - this->top - wid->pos_y;
1863 if (IsInsideMM(cursor_x, 0, wid->current_x) && IsInsideMM(cursor_y, 0, wid->current_y)) {
1864 Point pt = {cursor_x, cursor_y};
1865 this->SetZoomLevel((wheel < 0) ? ZLC_ZOOM_IN : ZLC_ZOOM_OUT, &pt);
1870 void OnScroll(Point delta) override
1872 if (_settings_client.gui.scroll_mode == VSM_VIEWPORT_RMB_FIXED || _settings_client.gui.scroll_mode == VSM_MAP_RMB_FIXED) _cursor.fix_at = true;
1874 /* While tile is at (delta.x, delta.y)? */
1875 int sub;
1876 Point pt = this->PixelToTile(delta.x, delta.y, &sub);
1877 this->SetNewScroll(this->scroll_x + pt.x * TILE_SIZE, this->scroll_y + pt.y * TILE_SIZE, sub);
1879 this->SetDirty();
1882 void OnMouseOver([[maybe_unused]] Point pt, WidgetID widget) override
1884 IndustryType new_highlight = INVALID_INDUSTRYTYPE;
1885 if (widget == WID_SM_LEGEND && this->map_type == SMT_INDUSTRY) {
1886 int industry_pos = GetPositionOnLegend(pt);
1887 if (industry_pos >= 0 && industry_pos < _smallmap_industry_count) {
1888 new_highlight = _legend_from_industries[industry_pos].type;
1891 if (new_highlight != _smallmap_industry_highlight) {
1892 _smallmap_industry_highlight = new_highlight;
1893 _smallmap_industry_highlight_state = true;
1894 this->SetDirty();
1900 SmallMapType SmallMapWindow::map_type = SMT_CONTOUR;
1901 bool SmallMapWindow::show_towns = true;
1902 bool SmallMapWindow::show_ind_names = false;
1903 int SmallMapWindow::map_height_limit = -1;
1906 * Custom container class for displaying smallmap with a vertically resizing legend panel.
1907 * The legend panel has a smallest height that depends on its width. Standard containers cannot handle this case.
1909 * @note The container assumes it has two children, the first is the display, the second is the bar with legends and selection image buttons.
1910 * Both children should be both horizontally and vertically resizable and horizontally fillable.
1911 * The bar should have a minimal size with a zero-size legends display. Child padding is not supported.
1913 class NWidgetSmallmapDisplay : public NWidgetContainer {
1914 const SmallMapWindow *smallmap_window; ///< Window manager instance.
1915 public:
1916 NWidgetSmallmapDisplay() : NWidgetContainer(NWID_VERTICAL)
1918 this->smallmap_window = nullptr;
1921 void SetupSmallestSize(Window *w) override
1923 assert(this->children.size() == 2);
1924 NWidgetBase *display = this->children.front().get();
1925 NWidgetBase *bar = this->children.back().get();
1927 display->SetupSmallestSize(w);
1928 bar->SetupSmallestSize(w);
1930 this->smallmap_window = dynamic_cast<SmallMapWindow *>(w);
1931 assert(this->smallmap_window != nullptr);
1932 this->smallest_x = std::max(display->smallest_x, bar->smallest_x + smallmap_window->GetMinLegendWidth());
1933 this->smallest_y = display->smallest_y + std::max(bar->smallest_y, smallmap_window->GetLegendHeight(smallmap_window->min_number_of_columns));
1934 this->fill_x = std::max(display->fill_x, bar->fill_x);
1935 this->fill_y = (display->fill_y == 0 && bar->fill_y == 0) ? 0 : std::min(display->fill_y, bar->fill_y);
1936 this->resize_x = std::max(display->resize_x, bar->resize_x);
1937 this->resize_y = std::min(display->resize_y, bar->resize_y);
1938 this->ApplyAspectRatio();
1941 void AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl) override
1943 this->pos_x = x;
1944 this->pos_y = y;
1945 this->current_x = given_width;
1946 this->current_y = given_height;
1948 assert(this->children.size() == 2);
1949 NWidgetBase *display = this->children.front().get();
1950 NWidgetBase *bar = this->children.back().get();
1952 if (sizing == ST_SMALLEST) {
1953 this->smallest_x = given_width;
1954 this->smallest_y = given_height;
1955 /* Make display and bar exactly equal to their minimal size. */
1956 display->AssignSizePosition(ST_SMALLEST, x, y, display->smallest_x, display->smallest_y, rtl);
1957 bar->AssignSizePosition(ST_SMALLEST, x, y + display->smallest_y, bar->smallest_x, bar->smallest_y, rtl);
1960 uint bar_height = std::max(bar->smallest_y, this->smallmap_window->GetLegendHeight(this->smallmap_window->GetNumberColumnsLegend(given_width - bar->smallest_x)));
1961 uint display_height = given_height - bar_height;
1962 display->AssignSizePosition(ST_RESIZE, x, y, given_width, display_height, rtl);
1963 bar->AssignSizePosition(ST_RESIZE, x, y + display_height, given_width, bar_height, rtl);
1967 /** Widget parts of the smallmap display. */
1968 static constexpr NWidgetPart _nested_smallmap_display[] = {
1969 NWidget(WWT_PANEL, COLOUR_BROWN, WID_SM_MAP_BORDER),
1970 NWidget(WWT_INSET, COLOUR_BROWN, WID_SM_MAP), SetMinimalSize(346, 140), SetResize(1, 1), SetPadding(2, 2, 2, 2), EndContainer(),
1971 EndContainer(),
1974 /** Widget parts of the smallmap legend bar + image buttons. */
1975 static constexpr NWidgetPart _nested_smallmap_bar[] = {
1976 NWidget(WWT_PANEL, COLOUR_BROWN),
1977 NWidget(NWID_HORIZONTAL),
1978 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SM_LEGEND), SetResize(1, 1),
1979 NWidget(NWID_VERTICAL),
1980 /* Top button row. */
1981 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1982 NWidget(WWT_PUSHIMGBTN, COLOUR_BROWN, WID_SM_ZOOM_IN),
1983 SetDataTip(SPR_IMG_ZOOMIN, STR_TOOLBAR_TOOLTIP_ZOOM_THE_VIEW_IN), SetFill(1, 1),
1984 NWidget(WWT_PUSHIMGBTN, COLOUR_BROWN, WID_SM_CENTERMAP),
1985 SetDataTip(SPR_IMG_SMALLMAP, STR_SMALLMAP_CENTER), SetFill(1, 1),
1986 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_BLANK),
1987 SetDataTip(SPR_EMPTY, STR_NULL), SetFill(1, 1),
1988 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_CONTOUR),
1989 SetDataTip(SPR_IMG_SHOW_COUNTOURS, STR_SMALLMAP_TOOLTIP_SHOW_LAND_CONTOURS_ON_MAP), SetFill(1, 1),
1990 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_VEHICLES),
1991 SetDataTip(SPR_IMG_SHOW_VEHICLES, STR_SMALLMAP_TOOLTIP_SHOW_VEHICLES_ON_MAP), SetFill(1, 1),
1992 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_INDUSTRIES),
1993 SetDataTip(SPR_IMG_INDUSTRY, STR_SMALLMAP_TOOLTIP_SHOW_INDUSTRIES_ON_MAP), SetFill(1, 1),
1994 EndContainer(),
1995 /* Bottom button row. */
1996 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1997 NWidget(WWT_PUSHIMGBTN, COLOUR_BROWN, WID_SM_ZOOM_OUT),
1998 SetDataTip(SPR_IMG_ZOOMOUT, STR_TOOLBAR_TOOLTIP_ZOOM_THE_VIEW_OUT), SetFill(1, 1),
1999 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_TOGGLETOWNNAME),
2000 SetDataTip(SPR_IMG_TOWN, STR_SMALLMAP_TOOLTIP_TOGGLE_TOWN_NAMES_ON_OFF), SetFill(1, 1),
2001 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_LINKSTATS),
2002 SetDataTip(SPR_IMG_CARGOFLOW, STR_SMALLMAP_TOOLTIP_SHOW_LINK_STATS_ON_MAP), SetFill(1, 1),
2003 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_ROUTES),
2004 SetDataTip(SPR_IMG_SHOW_ROUTES, STR_SMALLMAP_TOOLTIP_SHOW_TRANSPORT_ROUTES_ON), SetFill(1, 1),
2005 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_VEGETATION),
2006 SetDataTip(SPR_IMG_PLANTTREES, STR_SMALLMAP_TOOLTIP_SHOW_VEGETATION_ON_MAP), SetFill(1, 1),
2007 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_OWNERS),
2008 SetDataTip(SPR_IMG_COMPANY_GENERAL, STR_SMALLMAP_TOOLTIP_SHOW_LAND_OWNERS_ON_MAP), SetFill(1, 1),
2009 EndContainer(),
2010 NWidget(NWID_SPACER), SetResize(0, 1),
2011 EndContainer(),
2012 EndContainer(),
2013 EndContainer(),
2016 static std::unique_ptr<NWidgetBase> SmallMapDisplay()
2018 std::unique_ptr<NWidgetBase> map_display = std::make_unique<NWidgetSmallmapDisplay>();
2020 map_display = MakeNWidgets(_nested_smallmap_display, std::move(map_display));
2021 map_display = MakeNWidgets(_nested_smallmap_bar, std::move(map_display));
2022 return map_display;
2025 static constexpr NWidgetPart _nested_smallmap_widgets[] = {
2026 NWidget(NWID_HORIZONTAL),
2027 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
2028 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_SM_CAPTION), SetDataTip(STR_SMALLMAP_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2029 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
2030 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
2031 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
2032 EndContainer(),
2033 NWidgetFunction(SmallMapDisplay), // Smallmap display and legend bar + image buttons.
2034 /* Bottom button row and resize box. */
2035 NWidget(NWID_HORIZONTAL),
2036 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_SM_SELECT_BUTTONS),
2037 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
2038 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_SM_ENABLE_ALL), SetDataTip(STR_SMALLMAP_ENABLE_ALL, STR_NULL),
2039 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_SM_DISABLE_ALL), SetDataTip(STR_SMALLMAP_DISABLE_ALL, STR_NULL),
2040 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_SM_SHOW_HEIGHT), SetDataTip(STR_SMALLMAP_SHOW_HEIGHT, STR_SMALLMAP_TOOLTIP_SHOW_HEIGHT),
2042 /* 'show industry names' button and container. Only shown for the industry map type. */
2043 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_SM_SHOW_IND_NAMES_SEL),
2044 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_SM_SHOW_IND_NAMES), SetDataTip(STR_SMALLMAP_SHOW_INDUSTRY_NAMES, STR_SMALLMAP_TOOLTIP_SHOW_INDUSTRY_NAMES),
2045 EndContainer(),
2047 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(1, 0),
2048 EndContainer(),
2049 EndContainer(),
2050 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(1, 0),
2051 EndContainer(),
2052 EndContainer(),
2053 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
2054 EndContainer(),
2057 static WindowDesc _smallmap_desc(
2058 WDP_AUTO, "smallmap", 484, 314,
2059 WC_SMALLMAP, WC_NONE,
2061 _nested_smallmap_widgets
2065 * Show the smallmap window.
2067 void ShowSmallMap()
2069 AllocateWindowDescFront<SmallMapWindow>(_smallmap_desc, 0);
2073 * Scrolls the main window to given coordinates.
2074 * @param x x coordinate
2075 * @param y y coordinate
2076 * @param z z coordinate; -1 to scroll to terrain height
2077 * @param instant scroll instantly (meaningful only when smooth_scrolling is active)
2078 * @return did the viewport position change?
2080 bool ScrollMainWindowTo(int x, int y, int z, bool instant)
2082 bool res = ScrollWindowTo(x, y, z, GetMainWindow(), instant);
2084 /* If a user scrolls to a tile (via what way what so ever) and already is on
2085 * that tile (e.g.: pressed twice), move the smallmap to that location,
2086 * so you directly see where you are on the smallmap. */
2088 if (res) return res;
2090 SmallMapWindow *w = dynamic_cast<SmallMapWindow*>(FindWindowById(WC_SMALLMAP, 0));
2091 if (w != nullptr) w->SmallMapCenterOnCurrentPos();
2093 return res;
2097 * Determine the middle of a station in the smallmap window.
2098 * @param st The station we're looking for.
2099 * @return Middle point of the station in the smallmap window.
2101 Point GetSmallMapStationMiddle(const Window *w, const Station *st)
2103 return static_cast<const SmallMapWindow *>(w)->GetStationMiddle(st);