Update readme.md
[openttd-joker.git] / src / bridge_gui.cpp
blobaa35905344b549b6de0d15d1f1134af8c074ce51
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file bridge_gui.cpp Graphical user interface for bridge construction */
12 #include "stdafx.h"
13 #include "error.h"
14 #include "command_func.h"
15 #include "rail.h"
16 #include "road.h"
17 #include "strings_func.h"
18 #include "window_func.h"
19 #include "sound_func.h"
20 #include "gfx_func.h"
21 #include "tunnelbridge.h"
22 #include "sortlist_type.h"
23 #include "widgets/dropdown_func.h"
24 #include "core/geometry_func.hpp"
25 #include "cmd_helper.h"
26 #include "tunnelbridge_map.h"
27 #include "road_gui.h"
28 #include "tilehighlight_func.h"
30 #include "widgets/bridge_widget.h"
32 #include "table/strings.h"
34 #include "safeguards.h"
36 /** The type of the last built rail bridge */
37 static BridgeType _last_railbridge_type = 0;
38 /** The type of the last built road bridge */
39 static BridgeType _last_roadbridge_type = 0;
41 /**
42 * Carriage for the data we need if we want to build a bridge
44 struct BuildBridgeData {
45 BridgeType index;
46 const BridgeSpec *spec;
47 Money cost;
50 typedef GUIList<BuildBridgeData> GUIBridgeList; ///< List of bridges, used in #BuildBridgeWindow.
52 /**
53 * Callback executed after a build Bridge CMD has been called
55 * @param result Whether the build succeeded
56 * @param end_tile End tile of the bridge.
57 * @param p1 packed start tile coords (~ dx)
58 * @param p2 various bitstuffed elements
59 * - p2 = (bit 0- 7) - bridge type (hi bh)
60 * - p2 = (bit 8-12) - rail type or road types.
61 * - p2 = (bit 15-16) - transport type.
63 void CcBuildBridge(const CommandCost &result, TileIndex end_tile, uint32 p1, uint32 p2)
65 if (result.Failed()) return;
66 if (_settings_client.sound.confirm) SndPlayTileFx(SND_27_BLACKSMITH_ANVIL, end_tile);
68 TransportType transport_type = Extract<TransportType, 15, 2>(p2);
70 if (transport_type == TRANSPORT_ROAD) {
71 DiagDirection end_direction = ReverseDiagDir(GetTunnelBridgeDirection(end_tile));
72 ConnectRoadToStructure(end_tile, end_direction);
74 DiagDirection start_direction = ReverseDiagDir(GetTunnelBridgeDirection(p1));
75 ConnectRoadToStructure(p1, start_direction);
78 StoreRailPlacementEndpoints(p1, end_tile, (TileX(p1) == TileX(end_tile)) ? TRACK_Y : TRACK_X, false);
81 /** Window class for handling the bridge-build GUI. */
82 class BuildBridgeWindow : public Window {
83 private:
84 /* Runtime saved values */
85 static Listing last_sorting; ///< Last setting of the sort.
87 /* Constants for sorting the bridges */
88 static const StringID sorter_names[];
89 static GUIBridgeList::SortFunction * const sorter_funcs[];
91 /* Internal variables */
92 TileIndex start_tile;
93 TileIndex end_tile;
94 uint32 type;
95 GUIBridgeList *bridges;
96 int bridgetext_offset; ///< Horizontal offset of the text describing the bridge properties in #WID_BBS_BRIDGE_LIST relative to the left edge.
97 Scrollbar *vscroll;
99 /** Sort the bridges by their index */
100 static int CDECL BridgeIndexSorter(const BuildBridgeData *a, const BuildBridgeData *b)
102 return a->index - b->index;
105 /** Sort the bridges by their price */
106 static int CDECL BridgePriceSorter(const BuildBridgeData *a, const BuildBridgeData *b)
108 return a->cost - b->cost;
111 /** Sort the bridges by their maximum speed */
112 static int CDECL BridgeSpeedSorter(const BuildBridgeData *a, const BuildBridgeData *b)
114 return a->spec->speed - b->spec->speed;
117 void BuildBridge(uint8 i)
119 switch ((TransportType)(this->type >> 15)) {
120 case TRANSPORT_RAIL: _last_railbridge_type = this->bridges->Get(i)->index; break;
121 case TRANSPORT_ROAD: _last_roadbridge_type = this->bridges->Get(i)->index; break;
122 default: break;
124 DoCommandP(this->end_tile, this->start_tile, this->type | this->bridges->Get(i)->index,
125 CMD_BUILD_BRIDGE | CMD_MSG(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
128 /** Sort the builable bridges */
129 void SortBridgeList()
131 this->bridges->Sort();
133 /* Display the current sort variant */
134 this->GetWidget<NWidgetCore>(WID_BBS_DROPDOWN_CRITERIA)->widget_data = this->sorter_names[this->bridges->SortType()];
136 /* Set the modified widgets dirty */
137 this->SetWidgetDirty(WID_BBS_DROPDOWN_CRITERIA);
138 this->SetWidgetDirty(WID_BBS_BRIDGE_LIST);
141 public:
142 BuildBridgeWindow(WindowDesc *desc, TileIndex start, TileIndex end, uint32 br_type, GUIBridgeList *bl) : Window(desc),
143 start_tile(start),
144 end_tile(end),
145 type(br_type),
146 bridges(bl)
148 this->CreateNestedTree();
149 this->vscroll = this->GetScrollbar(WID_BBS_SCROLLBAR);
150 /* Change the data, or the caption of the gui. Set it to road or rail, accordingly. */
151 this->GetWidget<NWidgetCore>(WID_BBS_CAPTION)->widget_data = (GB(this->type, 15, 2) == TRANSPORT_ROAD) ? STR_SELECT_ROAD_BRIDGE_CAPTION : STR_SELECT_RAIL_BRIDGE_CAPTION;
152 this->FinishInitNested(GB(br_type, 15, 2)); // Initializes 'this->bridgetext_offset'.
154 this->parent = FindWindowById(WC_BUILD_TOOLBAR, GB(this->type, 15, 2));
155 this->bridges->SetListing(this->last_sorting);
156 this->bridges->SetSortFuncs(this->sorter_funcs);
157 this->bridges->NeedResort();
158 this->SortBridgeList();
160 this->vscroll->SetCount(bl->Length());
163 ~BuildBridgeWindow()
165 this->last_sorting = this->bridges->GetListing();
167 delete bridges;
170 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
172 switch (widget) {
173 case WID_BBS_DROPDOWN_ORDER: {
174 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
175 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
176 d.height += padding.height;
177 *size = maxdim(*size, d);
178 break;
180 case WID_BBS_DROPDOWN_CRITERIA: {
181 Dimension d = {0, 0};
182 for (const StringID *str = this->sorter_names; *str != INVALID_STRING_ID; str++) {
183 d = maxdim(d, GetStringBoundingBox(*str));
185 d.width += padding.width;
186 d.height += padding.height;
187 *size = maxdim(*size, d);
188 break;
190 case WID_BBS_BRIDGE_LIST: {
191 Dimension sprite_dim = {0, 0}; // Biggest bridge sprite dimension
192 Dimension text_dim = {0, 0}; // Biggest text dimension
193 for (int i = 0; i < (int)this->bridges->Length(); i++) {
194 const BridgeSpec *b = this->bridges->Get(i)->spec;
195 sprite_dim = maxdim(sprite_dim, GetSpriteSize(b->sprite));
197 SetDParam(2, this->bridges->Get(i)->cost);
198 SetDParam(1, b->speed);
199 SetDParam(0, b->material);
200 text_dim = maxdim(text_dim, GetStringBoundingBox(_game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO));
202 sprite_dim.height++; // Sprite is rendered one pixel down in the matrix field.
203 text_dim.height++; // Allowing the bottom row pixels to be rendered on the edge of the matrix field.
204 resize->height = max(sprite_dim.height, text_dim.height) + 2; // Max of both sizes + account for matrix edges.
206 this->bridgetext_offset = WD_MATRIX_LEFT + sprite_dim.width + 1; // Left edge of text, 1 pixel distance from the sprite.
207 size->width = this->bridgetext_offset + text_dim.width + WD_MATRIX_RIGHT;
208 size->height = 4 * resize->height; // Smallest bridge gui is 4 entries high in the matrix.
209 break;
214 virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
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 virtual void DrawWidget(const Rect &r, int widget) const
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 uint y = r.top;
233 for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < (int)this->bridges->Length(); i++) {
234 const BridgeSpec *b = this->bridges->Get(i)->spec;
236 SetDParam(2, this->bridges->Get(i)->cost);
237 SetDParam(1, b->speed);
238 SetDParam(0, b->material);
240 DrawSprite(b->sprite, b->pal, r.left + WD_MATRIX_LEFT, y + this->resize.step_height - 1 - GetSpriteSize(b->sprite).height);
241 DrawStringMultiLine(r.left + this->bridgetext_offset, r.right, y + 2, y + this->resize.step_height,
242 _game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO);
243 y += this->resize.step_height;
245 break;
250 virtual EventState OnKeyPress(WChar key, uint16 keycode)
252 const uint8 i = keycode - '1';
253 if (i < 9 && i < this->bridges->Length()) {
254 /* Build the requested bridge */
255 this->BuildBridge(i);
256 delete this;
257 return ES_HANDLED;
259 return ES_NOT_HANDLED;
262 virtual void OnClick(Point pt, int widget, int click_count)
264 switch (widget) {
265 default: break;
266 case WID_BBS_BRIDGE_LIST: {
267 uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_BBS_BRIDGE_LIST);
268 if (i < this->bridges->Length()) {
269 this->BuildBridge(i);
270 delete this;
272 break;
275 case WID_BBS_DROPDOWN_ORDER:
276 this->bridges->ToggleSortOrder();
277 this->SetDirty();
278 break;
280 case WID_BBS_DROPDOWN_CRITERIA:
281 ShowDropDownMenu(this, this->sorter_names, this->bridges->SortType(), WID_BBS_DROPDOWN_CRITERIA, 0, 0);
282 break;
286 virtual void OnDropdownSelect(int widget, int index)
288 if (widget == WID_BBS_DROPDOWN_CRITERIA && this->bridges->SortType() != index) {
289 this->bridges->SetSortType(index);
291 this->SortBridgeList();
295 virtual void OnResize()
297 this->vscroll->SetCapacityFromWidget(this, WID_BBS_BRIDGE_LIST);
301 /** Set the default sorting for the bridges */
302 Listing BuildBridgeWindow::last_sorting = {true, 2};
304 /** Available bridge sorting functions. */
305 GUIBridgeList::SortFunction * const BuildBridgeWindow::sorter_funcs[] = {
306 &BridgeIndexSorter,
307 &BridgePriceSorter,
308 &BridgeSpeedSorter
311 /** Names of the sorting functions. */
312 const StringID BuildBridgeWindow::sorter_names[] = {
313 STR_SORT_BY_NUMBER,
314 STR_SORT_BY_COST,
315 STR_SORT_BY_MAX_SPEED,
316 INVALID_STRING_ID
319 /** Widgets of the bridge gui. */
320 static const NWidgetPart _nested_build_bridge_widgets[] = {
321 /* Header */
322 NWidget(NWID_HORIZONTAL),
323 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
324 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_BBS_CAPTION), SetDataTip(STR_SELECT_RAIL_BRIDGE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
325 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
326 EndContainer(),
328 NWidget(NWID_HORIZONTAL),
329 NWidget(NWID_VERTICAL),
330 /* Sort order + criteria buttons */
331 NWidget(NWID_HORIZONTAL),
332 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_BBS_DROPDOWN_ORDER), SetFill(1, 0), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
333 NWidget(WWT_DROPDOWN, COLOUR_DARK_GREEN, WID_BBS_DROPDOWN_CRITERIA), SetFill(1, 0), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
334 EndContainer(),
335 /* Matrix. */
336 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),
337 EndContainer(),
339 /* scrollbar + resize button */
340 NWidget(NWID_VERTICAL),
341 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_BBS_SCROLLBAR),
342 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
343 EndContainer(),
344 EndContainer(),
347 /** Window definition for the rail bridge selection window. */
348 static WindowDesc _build_bridge_desc(
349 WDP_AUTO, "build_bridge", 200, 114,
350 WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
351 WDF_CONSTRUCTION,
352 _nested_build_bridge_widgets, lengthof(_nested_build_bridge_widgets)
356 * Prepare the data for the build a bridge window.
357 * If we can't build a bridge under the given conditions
358 * show an error message.
360 * @param start The start tile of the bridge
361 * @param end The end tile of the bridge
362 * @param transport_type The transport type
363 * @param road_rail_type The road/rail type
365 void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type)
367 DeleteWindowByClass(WC_BUILD_BRIDGE);
369 /* Data type for the bridge.
370 * Bit 16,15 = transport type,
371 * 14..8 = road/rail types,
372 * 7..0 = type of bridge */
373 uint32 type = (transport_type << 15) | (road_rail_type << 8);
375 /* The bridge length without ramps. */
376 const uint bridge_len = GetTunnelBridgeLength(start, end);
378 /* If Ctrl is being pressed, check whether the last bridge built is available
379 * If so, return this bridge type. Otherwise continue normally.
380 * We store bridge types for each transport type, so we have to check for
381 * the transport type beforehand.
383 BridgeType last_bridge_type = 0;
384 switch (transport_type) {
385 case TRANSPORT_ROAD: last_bridge_type = _last_roadbridge_type; break;
386 case TRANSPORT_RAIL: last_bridge_type = _last_railbridge_type; break;
387 default: break; // water ways and air routes don't have bridge types
389 if (_ctrl_pressed && CheckBridgeAvailability(last_bridge_type, bridge_len).Succeeded()) {
390 DoCommandP(end, start, type | last_bridge_type, CMD_BUILD_BRIDGE | CMD_MSG(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
391 return;
394 /* only query bridge building possibility once, result is the same for all bridges!
395 * returns CommandError() on failure, and price on success */
396 StringID errmsg = INVALID_STRING_ID;
397 CommandCost ret = DoCommand(end, start, type, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)) | DC_QUERY_COST, CMD_BUILD_BRIDGE);
399 GUIBridgeList *bl = nullptr;
400 if (ret.Failed()) {
401 errmsg = ret.GetErrorMessage();
402 } else {
403 /* check which bridges can be built */
404 const uint tot_bridgedata_len = CalcBridgeLenCostFactor(bridge_len + 2);
406 bl = new GUIBridgeList();
408 Money infra_cost = 0;
409 switch (transport_type) {
410 case TRANSPORT_ROAD: {
411 /* In case we add a new road type as well, we must be aware of those costs. */
412 RoadTypeIdentifiers rtids;
413 if (IsBridgeTile(start)) rtids = RoadTypeIdentifiers::FromTile(start);
414 rtids.MergeRoadType(RoadTypeIdentifier::Unpack(road_rail_type));
415 RoadTypeIdentifier rtid;
416 FOR_EACH_SET_ROADTYPEIDENTIFIER(rtid, rtids) {
417 infra_cost += (bridge_len + 2) * 2 * RoadBuildCost(rtid);
419 break;
421 case TRANSPORT_RAIL: infra_cost = (bridge_len + 2) * RailBuildCost((RailType)road_rail_type); break;
422 default: break;
425 /* loop for all bridgetypes */
426 for (BridgeType brd_type = 0; brd_type != MAX_BRIDGES; brd_type++) {
427 if (CheckBridgeAvailability(brd_type, bridge_len).Succeeded()) {
428 /* bridge is accepted, add to list */
429 BuildBridgeData *item = bl->Append();
430 item->index = brd_type;
431 item->spec = GetBridgeSpec(brd_type);
432 /* Add to terraforming & bulldozing costs the cost of the
433 * bridge itself (not computed with DC_QUERY_COST) */
434 item->cost = ret.GetCost() + (((int64)tot_bridgedata_len * _price[PR_BUILD_BRIDGE] * item->spec->price) >> 8) + infra_cost;
439 if (bl != nullptr && bl->Length() != 0) {
440 new BuildBridgeWindow(&_build_bridge_desc, start, end, type, bl);
441 } else {
442 delete bl;
443 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, errmsg, WL_INFO, TileX(end) * TILE_SIZE, TileY(end) * TILE_SIZE);