Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / bridge_gui.cpp
blobfec724bb4c0d55eb98b61d1914eb916b607a1343
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 bridge_gui.cpp Graphical user interface for bridge construction */
10 #include "stdafx.h"
11 #include "error.h"
12 #include "command_func.h"
13 #include "rail.h"
14 #include "road.h"
15 #include "strings_func.h"
16 #include "window_func.h"
17 #include "sound_func.h"
18 #include "gfx_func.h"
19 #include "tunnelbridge.h"
20 #include "sortlist_type.h"
21 #include "widgets/dropdown_func.h"
22 #include "core/geometry_func.hpp"
23 #include "tunnelbridge_map.h"
24 #include "road_gui.h"
25 #include "tunnelbridge_cmd.h"
27 #include "widgets/bridge_widget.h"
29 #include "table/strings.h"
31 #include "safeguards.h"
33 /** The type of the last built rail bridge */
34 static BridgeType _last_railbridge_type = 0;
35 /** The type of the last built road bridge */
36 static BridgeType _last_roadbridge_type = 0;
38 /**
39 * Carriage for the data we need if we want to build a bridge
41 struct BuildBridgeData {
42 BridgeType index;
43 const BridgeSpec *spec;
44 Money cost;
47 typedef GUIList<BuildBridgeData> GUIBridgeList; ///< List of bridges, used in #BuildBridgeWindow.
49 /**
50 * Callback executed after a build Bridge CMD has been called
52 * @param result Whether the build succeeded
53 * @param end_tile End tile of the bridge.
54 * @param tile_start start tile
55 * @param transport_type transport type.
57 void CcBuildBridge(Commands, const CommandCost &result, TileIndex end_tile, TileIndex tile_start, TransportType transport_type, BridgeType, byte)
59 if (result.Failed()) return;
60 if (_settings_client.sound.confirm) SndPlayTileFx(SND_27_CONSTRUCTION_BRIDGE, end_tile);
62 if (transport_type == TRANSPORT_ROAD) {
63 DiagDirection end_direction = ReverseDiagDir(GetTunnelBridgeDirection(end_tile));
64 ConnectRoadToStructure(end_tile, end_direction);
66 DiagDirection start_direction = ReverseDiagDir(GetTunnelBridgeDirection(tile_start));
67 ConnectRoadToStructure(tile_start, start_direction);
71 /** Window class for handling the bridge-build GUI. */
72 class BuildBridgeWindow : public Window {
73 private:
74 /* Runtime saved values */
75 static Listing last_sorting; ///< Last setting of the sort.
77 /* Constants for sorting the bridges */
78 static const StringID sorter_names[];
79 static GUIBridgeList::SortFunction * const sorter_funcs[];
81 /* Internal variables */
82 TileIndex start_tile;
83 TileIndex end_tile;
84 TransportType transport_type;
85 byte road_rail_type;
86 GUIBridgeList bridges;
87 int icon_width; ///< Scaled width of the the bridge icon sprite.
88 Scrollbar *vscroll;
90 /** Sort the bridges by their index */
91 static bool BridgeIndexSorter(const BuildBridgeData &a, const BuildBridgeData &b)
93 return a.index < b.index;
96 /** Sort the bridges by their price */
97 static bool BridgePriceSorter(const BuildBridgeData &a, const BuildBridgeData &b)
99 return a.cost < b.cost;
102 /** Sort the bridges by their maximum speed */
103 static bool BridgeSpeedSorter(const BuildBridgeData &a, const BuildBridgeData &b)
105 return a.spec->speed < b.spec->speed;
108 void BuildBridge(BridgeType type)
110 switch (this->transport_type) {
111 case TRANSPORT_RAIL: _last_railbridge_type = type; break;
112 case TRANSPORT_ROAD: _last_roadbridge_type = type; break;
113 default: break;
115 Command<CMD_BUILD_BRIDGE>::Post(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, CcBuildBridge,
116 this->end_tile, this->start_tile, this->transport_type, type, this->road_rail_type);
119 /** Sort the builable bridges */
120 void SortBridgeList()
122 this->bridges.Sort();
124 /* Display the current sort variant */
125 this->GetWidget<NWidgetCore>(WID_BBS_DROPDOWN_CRITERIA)->widget_data = this->sorter_names[this->bridges.SortType()];
127 /* Set the modified widgets dirty */
128 this->SetWidgetDirty(WID_BBS_DROPDOWN_CRITERIA);
129 this->SetWidgetDirty(WID_BBS_BRIDGE_LIST);
133 * Get the StringID to draw in the selection list and set the appropriate DParams.
134 * @param bridge_data the bridge to get the StringID of.
135 * @return the StringID.
137 StringID GetBridgeSelectString(const BuildBridgeData &bridge_data) const
139 SetDParam(0, bridge_data.spec->material);
140 SetDParam(1, PackVelocity(bridge_data.spec->speed, static_cast<VehicleType>(this->transport_type)));
141 SetDParam(2, bridge_data.cost);
142 /* If the bridge has no meaningful speed limit, don't display it. */
143 if (bridge_data.spec->speed == UINT16_MAX) {
144 return _game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_INFO_NAME : STR_SELECT_BRIDGE_INFO_NAME_COST;
146 return _game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_INFO_NAME_MAX_SPEED : STR_SELECT_BRIDGE_INFO_NAME_MAX_SPEED_COST;
149 public:
150 BuildBridgeWindow(WindowDesc *desc, TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type, GUIBridgeList &&bl) : Window(desc),
151 start_tile(start),
152 end_tile(end),
153 transport_type(transport_type),
154 road_rail_type(road_rail_type),
155 bridges(std::move(bl))
157 this->CreateNestedTree();
158 this->vscroll = this->GetScrollbar(WID_BBS_SCROLLBAR);
159 /* Change the data, or the caption of the gui. Set it to road or rail, accordingly. */
160 this->GetWidget<NWidgetCore>(WID_BBS_CAPTION)->widget_data = (transport_type == TRANSPORT_ROAD) ? STR_SELECT_ROAD_BRIDGE_CAPTION : STR_SELECT_RAIL_BRIDGE_CAPTION;
161 this->FinishInitNested(transport_type); // Initializes 'this->icon_width'.
163 this->parent = FindWindowById(WC_BUILD_TOOLBAR, transport_type);
164 this->bridges.SetListing(this->last_sorting);
165 this->bridges.SetSortFuncs(this->sorter_funcs);
166 this->bridges.NeedResort();
167 this->SortBridgeList();
169 this->vscroll->SetCount(this->bridges.size());
172 ~BuildBridgeWindow()
174 this->last_sorting = this->bridges.GetListing();
177 void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
179 switch (widget) {
180 case WID_BBS_DROPDOWN_ORDER: {
181 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
182 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
183 d.height += padding.height;
184 *size = maxdim(*size, d);
185 break;
187 case WID_BBS_DROPDOWN_CRITERIA: {
188 Dimension d = {0, 0};
189 for (const StringID *str = this->sorter_names; *str != INVALID_STRING_ID; str++) {
190 d = maxdim(d, GetStringBoundingBox(*str));
192 d.width += padding.width;
193 d.height += padding.height;
194 *size = maxdim(*size, d);
195 break;
197 case WID_BBS_BRIDGE_LIST: {
198 Dimension sprite_dim = {0, 0}; // Biggest bridge sprite dimension
199 Dimension text_dim = {0, 0}; // Biggest text dimension
200 for (const BuildBridgeData &bridge_data : this->bridges) {
201 sprite_dim = maxdim(sprite_dim, GetScaledSpriteSize(bridge_data.spec->sprite));
202 text_dim = maxdim(text_dim, GetStringBoundingBox(GetBridgeSelectString(bridge_data)));
204 resize->height = std::max(sprite_dim.height, text_dim.height) + padding.height; // Max of both sizes + account for matrix edges.
206 this->icon_width = sprite_dim.width; // Width of bridge icon.
207 size->width = this->icon_width + WidgetDimensions::scaled.hsep_normal + text_dim.width + padding.width;
208 size->height = 4 * resize->height; // Smallest bridge gui is 4 entries high in the matrix.
209 break;
214 Point OnInitialPosition([[maybe_unused]] int16_t sm_width, [[maybe_unused]] int16_t sm_height, [[maybe_unused]] int window_number) override
216 /* Position the window so hopefully the first bridge from the list is under the mouse pointer. */
217 NWidgetBase *list = this->GetWidget<NWidgetBase>(WID_BBS_BRIDGE_LIST);
218 Point corner; // point of the top left corner of the window.
219 corner.y = Clamp(_cursor.pos.y - list->pos_y - 5, GetMainViewTop(), GetMainViewBottom() - sm_height);
220 corner.x = Clamp(_cursor.pos.x - list->pos_x - 5, 0, _screen.width - sm_width);
221 return corner;
224 void DrawWidget(const Rect &r, WidgetID widget) const override
226 switch (widget) {
227 case WID_BBS_DROPDOWN_ORDER:
228 this->DrawSortButtonState(widget, this->bridges.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
229 break;
231 case WID_BBS_BRIDGE_LIST: {
232 Rect tr = r.WithHeight(this->resize.step_height).Shrink(WidgetDimensions::scaled.matrix);
233 bool rtl = _current_text_dir == TD_RTL;
234 for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < (int)this->bridges.size(); i++) {
235 const BuildBridgeData &bridge_data = this->bridges.at(i);
236 const BridgeSpec *b = bridge_data.spec;
237 DrawSpriteIgnorePadding(b->sprite, b->pal, tr.WithWidth(this->icon_width, rtl), SA_HOR_CENTER | SA_BOTTOM);
238 DrawStringMultiLine(tr.Indent(this->icon_width + WidgetDimensions::scaled.hsep_normal, rtl), GetBridgeSelectString(bridge_data));
239 tr = tr.Translate(0, this->resize.step_height);
241 break;
246 EventState OnKeyPress([[maybe_unused]] char32_t key, uint16_t keycode) override
248 const uint8_t i = keycode - '1';
249 if (i < 9 && i < this->bridges.size()) {
250 /* Build the requested bridge */
251 this->BuildBridge(this->bridges[i].index);
252 this->Close();
253 return ES_HANDLED;
255 return ES_NOT_HANDLED;
258 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
260 switch (widget) {
261 default: break;
262 case WID_BBS_BRIDGE_LIST: {
263 auto it = this->vscroll->GetScrolledItemFromWidget(this->bridges, pt.y, this, WID_BBS_BRIDGE_LIST);
264 if (it != this->bridges.end()) {
265 this->BuildBridge(it->index);
266 this->Close();
268 break;
271 case WID_BBS_DROPDOWN_ORDER:
272 this->bridges.ToggleSortOrder();
273 this->SetDirty();
274 break;
276 case WID_BBS_DROPDOWN_CRITERIA:
277 ShowDropDownMenu(this, this->sorter_names, this->bridges.SortType(), WID_BBS_DROPDOWN_CRITERIA, 0, 0);
278 break;
282 void OnDropdownSelect(WidgetID widget, int index) override
284 if (widget == WID_BBS_DROPDOWN_CRITERIA && this->bridges.SortType() != index) {
285 this->bridges.SetSortType(index);
287 this->SortBridgeList();
291 void OnResize() override
293 this->vscroll->SetCapacityFromWidget(this, WID_BBS_BRIDGE_LIST);
297 /** Set the default sorting for the bridges */
298 Listing BuildBridgeWindow::last_sorting = {true, 2};
300 /** Available bridge sorting functions. */
301 GUIBridgeList::SortFunction * const BuildBridgeWindow::sorter_funcs[] = {
302 &BridgeIndexSorter,
303 &BridgePriceSorter,
304 &BridgeSpeedSorter
307 /** Names of the sorting functions. */
308 const StringID BuildBridgeWindow::sorter_names[] = {
309 STR_SORT_BY_NUMBER,
310 STR_SORT_BY_COST,
311 STR_SORT_BY_MAX_SPEED,
312 INVALID_STRING_ID
315 /** Widgets of the bridge gui. */
316 static constexpr NWidgetPart _nested_build_bridge_widgets[] = {
317 /* Header */
318 NWidget(NWID_HORIZONTAL),
319 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
320 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_BBS_CAPTION), SetDataTip(STR_SELECT_RAIL_BRIDGE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
321 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
322 EndContainer(),
324 NWidget(NWID_HORIZONTAL),
325 NWidget(NWID_VERTICAL),
326 /* Sort order + criteria buttons */
327 NWidget(NWID_HORIZONTAL),
328 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_BBS_DROPDOWN_ORDER), SetFill(1, 0), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
329 NWidget(WWT_DROPDOWN, COLOUR_DARK_GREEN, WID_BBS_DROPDOWN_CRITERIA), SetFill(1, 0), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
330 EndContainer(),
331 /* Matrix. */
332 NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, WID_BBS_BRIDGE_LIST), SetFill(1, 0), SetResize(0, 22), SetMatrixDataTip(1, 0, STR_SELECT_BRIDGE_SELECTION_TOOLTIP), SetScrollbar(WID_BBS_SCROLLBAR),
333 EndContainer(),
335 /* scrollbar + resize button */
336 NWidget(NWID_VERTICAL),
337 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_BBS_SCROLLBAR),
338 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
339 EndContainer(),
340 EndContainer(),
343 /** Window definition for the rail bridge selection window. */
344 static WindowDesc _build_bridge_desc(__FILE__, __LINE__,
345 WDP_AUTO, "build_bridge", 200, 114,
346 WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
347 WDF_CONSTRUCTION,
348 std::begin(_nested_build_bridge_widgets), std::end(_nested_build_bridge_widgets)
352 * Prepare the data for the build a bridge window.
353 * If we can't build a bridge under the given conditions
354 * show an error message.
356 * @param start The start tile of the bridge
357 * @param end The end tile of the bridge
358 * @param transport_type The transport type
359 * @param road_rail_type The road/rail type
361 void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type)
363 CloseWindowByClass(WC_BUILD_BRIDGE);
365 /* The bridge length without ramps. */
366 const uint bridge_len = GetTunnelBridgeLength(start, end);
368 /* If Ctrl is being pressed, check whether the last bridge built is available
369 * If so, return this bridge type. Otherwise continue normally.
370 * We store bridge types for each transport type, so we have to check for
371 * the transport type beforehand.
373 BridgeType last_bridge_type = 0;
374 switch (transport_type) {
375 case TRANSPORT_ROAD: last_bridge_type = _last_roadbridge_type; break;
376 case TRANSPORT_RAIL: last_bridge_type = _last_railbridge_type; break;
377 default: break; // water ways and air routes don't have bridge types
379 if (_ctrl_pressed && CheckBridgeAvailability(last_bridge_type, bridge_len).Succeeded()) {
380 Command<CMD_BUILD_BRIDGE>::Post(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, CcBuildBridge, end, start, transport_type, last_bridge_type, road_rail_type);
381 return;
384 /* only query bridge building possibility once, result is the same for all bridges!
385 * returns CMD_ERROR on failure, and price on success */
386 StringID errmsg = INVALID_STRING_ID;
387 CommandCost ret = Command<CMD_BUILD_BRIDGE>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_BRIDGE>()) | DC_QUERY_COST, end, start, transport_type, 0, road_rail_type);
389 GUIBridgeList bl;
390 if (ret.Failed()) {
391 errmsg = ret.GetErrorMessage();
392 } else {
393 /* check which bridges can be built */
394 const uint tot_bridgedata_len = CalcBridgeLenCostFactor(bridge_len + 2);
396 Money infra_cost = 0;
397 switch (transport_type) {
398 case TRANSPORT_ROAD: {
399 /* In case we add a new road type as well, we must be aware of those costs. */
400 RoadType road_rt = INVALID_ROADTYPE;
401 RoadType tram_rt = INVALID_ROADTYPE;
402 if (IsBridgeTile(start)) {
403 road_rt = GetRoadTypeRoad(start);
404 tram_rt = GetRoadTypeTram(start);
406 if (RoadTypeIsRoad((RoadType)road_rail_type)) {
407 road_rt = (RoadType)road_rail_type;
408 } else {
409 tram_rt = (RoadType)road_rail_type;
412 if (road_rt != INVALID_ROADTYPE) infra_cost += (bridge_len + 2) * 2 * RoadBuildCost(road_rt);
413 if (tram_rt != INVALID_ROADTYPE) infra_cost += (bridge_len + 2) * 2 * RoadBuildCost(tram_rt);
415 break;
417 case TRANSPORT_RAIL: infra_cost = (bridge_len + 2) * RailBuildCost((RailType)road_rail_type); break;
418 default: break;
421 bool any_available = false;
422 CommandCost type_check;
423 /* loop for all bridgetypes */
424 for (BridgeType brd_type = 0; brd_type != MAX_BRIDGES; brd_type++) {
425 type_check = CheckBridgeAvailability(brd_type, bridge_len);
426 if (type_check.Succeeded()) {
427 /* bridge is accepted, add to list */
428 BuildBridgeData &item = bl.emplace_back();
429 item.index = brd_type;
430 item.spec = GetBridgeSpec(brd_type);
431 /* Add to terraforming & bulldozing costs the cost of the
432 * bridge itself (not computed with DC_QUERY_COST) */
433 item.cost = ret.GetCost() + (((int64_t)tot_bridgedata_len * _price[PR_BUILD_BRIDGE] * item.spec->price) >> 8) + infra_cost;
434 any_available = true;
437 /* give error cause if no bridges available here*/
438 if (!any_available)
440 errmsg = type_check.GetErrorMessage();
444 if (!bl.empty()) {
445 new BuildBridgeWindow(&_build_bridge_desc, start, end, transport_type, road_rail_type, std::move(bl));
446 } else {
447 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, errmsg, WL_INFO, TileX(end) * TILE_SIZE, TileY(end) * TILE_SIZE);