Add standard library header includes to precompiled header. Fix several uses of strin...
[openttd-joker.git] / src / bridge_gui.cpp
blob3d64154a600e58dc77024bcc1f15af6781ebf2e7
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 "strings_func.h"
17 #include "window_func.h"
18 #include "sound_func.h"
19 #include "gfx_func.h"
20 #include "tunnelbridge.h"
21 #include "sortlist_type.h"
22 #include "widgets/dropdown_func.h"
23 #include "core/geometry_func.hpp"
24 #include "cmd_helper.h"
25 #include "tunnelbridge_map.h"
26 #include "road_gui.h"
27 #include "tilehighlight_func.h"
29 #include "widgets/bridge_widget.h"
31 #include "table/strings.h"
33 #include "safeguards.h"
35 /** The type of the last built rail bridge */
36 static BridgeType _last_railbridge_type = 0;
37 /** The type of the last built road bridge */
38 static BridgeType _last_roadbridge_type = 0;
40 /**
41 * Carriage for the data we need if we want to build a bridge
43 struct BuildBridgeData {
44 BridgeType index;
45 const BridgeSpec *spec;
46 Money cost;
49 typedef GUIList<BuildBridgeData> GUIBridgeList; ///< List of bridges, used in #BuildBridgeWindow.
51 /**
52 * Callback executed after a build Bridge CMD has been called
54 * @param result Whether the build succeeded
55 * @param end_tile End tile of the bridge.
56 * @param p1 packed start tile coords (~ dx)
57 * @param p2 various bitstuffed elements
58 * - p2 = (bit 0- 7) - bridge type (hi bh)
59 * - p2 = (bit 8-12) - rail type or road types.
60 * - p2 = (bit 15-16) - transport type.
62 void CcBuildBridge(const CommandCost &result, TileIndex end_tile, uint32 p1, uint32 p2)
64 if (result.Failed()) return;
65 if (_settings_client.sound.confirm) SndPlayTileFx(SND_27_BLACKSMITH_ANVIL, end_tile);
67 TransportType transport_type = Extract<TransportType, 15, 2>(p2);
69 if (transport_type == TRANSPORT_ROAD) {
70 DiagDirection end_direction = ReverseDiagDir(GetTunnelBridgeDirection(end_tile));
71 ConnectRoadToStructure(end_tile, end_direction);
73 DiagDirection start_direction = ReverseDiagDir(GetTunnelBridgeDirection(p1));
74 ConnectRoadToStructure(p1, start_direction);
77 StoreRailPlacementEndpoints(p1, end_tile, (TileX(p1) == TileX(end_tile)) ? TRACK_Y : TRACK_X, false);
80 /** Window class for handling the bridge-build GUI. */
81 class BuildBridgeWindow : public Window {
82 private:
83 /* Runtime saved values */
84 static Listing last_sorting; ///< Last setting of the sort.
86 /* Constants for sorting the bridges */
87 static const StringID sorter_names[];
88 static GUIBridgeList::SortFunction * const sorter_funcs[];
90 /* Internal variables */
91 TileIndex start_tile;
92 TileIndex end_tile;
93 uint32 type;
94 GUIBridgeList *bridges;
95 int bridgetext_offset; ///< Horizontal offset of the text describing the bridge properties in #WID_BBS_BRIDGE_LIST relative to the left edge.
96 Scrollbar *vscroll;
98 /** Sort the bridges by their index */
99 static int CDECL BridgeIndexSorter(const BuildBridgeData *a, const BuildBridgeData *b)
101 return a->index - b->index;
104 /** Sort the bridges by their price */
105 static int CDECL BridgePriceSorter(const BuildBridgeData *a, const BuildBridgeData *b)
107 return a->cost - b->cost;
110 /** Sort the bridges by their maximum speed */
111 static int CDECL BridgeSpeedSorter(const BuildBridgeData *a, const BuildBridgeData *b)
113 return a->spec->speed - b->spec->speed;
116 void BuildBridge(uint8 i)
118 switch ((TransportType)(this->type >> 15)) {
119 case TRANSPORT_RAIL: _last_railbridge_type = this->bridges->Get(i)->index; break;
120 case TRANSPORT_ROAD: _last_roadbridge_type = this->bridges->Get(i)->index; break;
121 default: break;
123 DoCommandP(this->end_tile, this->start_tile, this->type | this->bridges->Get(i)->index,
124 CMD_BUILD_BRIDGE | CMD_MSG(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
127 /** Sort the builable bridges */
128 void SortBridgeList()
130 this->bridges->Sort();
132 /* Display the current sort variant */
133 this->GetWidget<NWidgetCore>(WID_BBS_DROPDOWN_CRITERIA)->widget_data = this->sorter_names[this->bridges->SortType()];
135 /* Set the modified widgets dirty */
136 this->SetWidgetDirty(WID_BBS_DROPDOWN_CRITERIA);
137 this->SetWidgetDirty(WID_BBS_BRIDGE_LIST);
140 public:
141 BuildBridgeWindow(WindowDesc *desc, TileIndex start, TileIndex end, uint32 br_type, GUIBridgeList *bl) : Window(desc),
142 start_tile(start),
143 end_tile(end),
144 type(br_type),
145 bridges(bl)
147 this->CreateNestedTree();
148 this->vscroll = this->GetScrollbar(WID_BBS_SCROLLBAR);
149 /* Change the data, or the caption of the gui. Set it to road or rail, accordingly. */
150 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;
151 this->FinishInitNested(GB(br_type, 15, 2)); // Initializes 'this->bridgetext_offset'.
153 this->parent = FindWindowById(WC_BUILD_TOOLBAR, GB(this->type, 15, 2));
154 this->bridges->SetListing(this->last_sorting);
155 this->bridges->SetSortFuncs(this->sorter_funcs);
156 this->bridges->NeedResort();
157 this->SortBridgeList();
159 this->vscroll->SetCount(bl->Length());
162 ~BuildBridgeWindow()
164 this->last_sorting = this->bridges->GetListing();
166 delete bridges;
169 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
171 switch (widget) {
172 case WID_BBS_DROPDOWN_ORDER: {
173 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
174 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
175 d.height += padding.height;
176 *size = maxdim(*size, d);
177 break;
179 case WID_BBS_DROPDOWN_CRITERIA: {
180 Dimension d = {0, 0};
181 for (const StringID *str = this->sorter_names; *str != INVALID_STRING_ID; str++) {
182 d = maxdim(d, GetStringBoundingBox(*str));
184 d.width += padding.width;
185 d.height += padding.height;
186 *size = maxdim(*size, d);
187 break;
189 case WID_BBS_BRIDGE_LIST: {
190 Dimension sprite_dim = {0, 0}; // Biggest bridge sprite dimension
191 Dimension text_dim = {0, 0}; // Biggest text dimension
192 for (int i = 0; i < (int)this->bridges->Length(); i++) {
193 const BridgeSpec *b = this->bridges->Get(i)->spec;
194 sprite_dim = maxdim(sprite_dim, GetSpriteSize(b->sprite));
196 SetDParam(2, this->bridges->Get(i)->cost);
197 SetDParam(1, b->speed);
198 SetDParam(0, b->material);
199 text_dim = maxdim(text_dim, GetStringBoundingBox(_game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO));
201 sprite_dim.height++; // Sprite is rendered one pixel down in the matrix field.
202 text_dim.height++; // Allowing the bottom row pixels to be rendered on the edge of the matrix field.
203 resize->height = max(sprite_dim.height, text_dim.height) + 2; // Max of both sizes + account for matrix edges.
205 this->bridgetext_offset = WD_MATRIX_LEFT + sprite_dim.width + 1; // Left edge of text, 1 pixel distance from the sprite.
206 size->width = this->bridgetext_offset + text_dim.width + WD_MATRIX_RIGHT;
207 size->height = 4 * resize->height; // Smallest bridge gui is 4 entries high in the matrix.
208 break;
213 virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
215 /* Position the window so hopefully the first bridge from the list is under the mouse pointer. */
216 NWidgetBase *list = this->GetWidget<NWidgetBase>(WID_BBS_BRIDGE_LIST);
217 Point corner; // point of the top left corner of the window.
218 corner.y = Clamp(_cursor.pos.y - list->pos_y - 5, GetMainViewTop(), GetMainViewBottom() - sm_height);
219 corner.x = Clamp(_cursor.pos.x - list->pos_x - 5, 0, _screen.width - sm_width);
220 return corner;
223 virtual void DrawWidget(const Rect &r, int widget) const
225 switch (widget) {
226 case WID_BBS_DROPDOWN_ORDER:
227 this->DrawSortButtonState(widget, this->bridges->IsDescSortOrder() ? SBS_DOWN : SBS_UP);
228 break;
230 case WID_BBS_BRIDGE_LIST: {
231 uint y = r.top;
232 for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < (int)this->bridges->Length(); i++) {
233 const BridgeSpec *b = this->bridges->Get(i)->spec;
235 SetDParam(2, this->bridges->Get(i)->cost);
236 SetDParam(1, b->speed);
237 SetDParam(0, b->material);
239 DrawSprite(b->sprite, b->pal, r.left + WD_MATRIX_LEFT, y + this->resize.step_height - 1 - GetSpriteSize(b->sprite).height);
240 DrawStringMultiLine(r.left + this->bridgetext_offset, r.right, y + 2, y + this->resize.step_height,
241 _game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO);
242 y += this->resize.step_height;
244 break;
249 virtual EventState OnKeyPress(WChar key, uint16 keycode)
251 const uint8 i = keycode - '1';
252 if (i < 9 && i < this->bridges->Length()) {
253 /* Build the requested bridge */
254 this->BuildBridge(i);
255 delete this;
256 return ES_HANDLED;
258 return ES_NOT_HANDLED;
261 virtual void OnClick(Point pt, int widget, int click_count)
263 switch (widget) {
264 default: break;
265 case WID_BBS_BRIDGE_LIST: {
266 uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_BBS_BRIDGE_LIST);
267 if (i < this->bridges->Length()) {
268 this->BuildBridge(i);
269 delete this;
271 break;
274 case WID_BBS_DROPDOWN_ORDER:
275 this->bridges->ToggleSortOrder();
276 this->SetDirty();
277 break;
279 case WID_BBS_DROPDOWN_CRITERIA:
280 ShowDropDownMenu(this, this->sorter_names, this->bridges->SortType(), WID_BBS_DROPDOWN_CRITERIA, 0, 0);
281 break;
285 virtual void OnDropdownSelect(int widget, int index)
287 if (widget == WID_BBS_DROPDOWN_CRITERIA && this->bridges->SortType() != index) {
288 this->bridges->SetSortType(index);
290 this->SortBridgeList();
294 virtual void OnResize()
296 this->vscroll->SetCapacityFromWidget(this, WID_BBS_BRIDGE_LIST);
300 /** Set the default sorting for the bridges */
301 Listing BuildBridgeWindow::last_sorting = {true, 2};
303 /** Available bridge sorting functions. */
304 GUIBridgeList::SortFunction * const BuildBridgeWindow::sorter_funcs[] = {
305 &BridgeIndexSorter,
306 &BridgePriceSorter,
307 &BridgeSpeedSorter
310 /** Names of the sorting functions. */
311 const StringID BuildBridgeWindow::sorter_names[] = {
312 STR_SORT_BY_NUMBER,
313 STR_SORT_BY_COST,
314 STR_SORT_BY_MAX_SPEED,
315 INVALID_STRING_ID
318 /** Widgets of the bridge gui. */
319 static const NWidgetPart _nested_build_bridge_widgets[] = {
320 /* Header */
321 NWidget(NWID_HORIZONTAL),
322 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
323 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_BBS_CAPTION), SetDataTip(STR_SELECT_RAIL_BRIDGE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
324 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
325 EndContainer(),
327 NWidget(NWID_HORIZONTAL),
328 NWidget(NWID_VERTICAL),
329 /* Sort order + criteria buttons */
330 NWidget(NWID_HORIZONTAL),
331 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_BBS_DROPDOWN_ORDER), SetFill(1, 0), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
332 NWidget(WWT_DROPDOWN, COLOUR_DARK_GREEN, WID_BBS_DROPDOWN_CRITERIA), SetFill(1, 0), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
333 EndContainer(),
334 /* Matrix. */
335 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),
336 EndContainer(),
338 /* scrollbar + resize button */
339 NWidget(NWID_VERTICAL),
340 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_BBS_SCROLLBAR),
341 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
342 EndContainer(),
343 EndContainer(),
346 /** Window definition for the rail bridge selection window. */
347 static WindowDesc _build_bridge_desc(
348 WDP_AUTO, "build_bridge", 200, 114,
349 WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
350 WDF_CONSTRUCTION,
351 _nested_build_bridge_widgets, lengthof(_nested_build_bridge_widgets)
355 * Prepare the data for the build a bridge window.
356 * If we can't build a bridge under the given conditions
357 * show an error message.
359 * @param start The start tile of the bridge
360 * @param end The end tile of the bridge
361 * @param transport_type The transport type
362 * @param road_rail_type The road/rail type
364 void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type)
366 DeleteWindowByClass(WC_BUILD_BRIDGE);
368 /* Data type for the bridge.
369 * Bit 16,15 = transport type,
370 * 14..8 = road/rail types,
371 * 7..0 = type of bridge */
372 uint32 type = (transport_type << 15) | (road_rail_type << 8);
374 /* The bridge length without ramps. */
375 const uint bridge_len = GetTunnelBridgeLength(start, end);
377 /* If Ctrl is being pressed, check whether the last bridge built is available
378 * If so, return this bridge type. Otherwise continue normally.
379 * We store bridge types for each transport type, so we have to check for
380 * the transport type beforehand.
382 BridgeType last_bridge_type = 0;
383 switch (transport_type) {
384 case TRANSPORT_ROAD: last_bridge_type = _last_roadbridge_type; break;
385 case TRANSPORT_RAIL: last_bridge_type = _last_railbridge_type; break;
386 default: break; // water ways and air routes don't have bridge types
388 if (_ctrl_pressed && CheckBridgeAvailability(last_bridge_type, bridge_len).Succeeded()) {
389 DoCommandP(end, start, type | last_bridge_type, CMD_BUILD_BRIDGE | CMD_MSG(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE), CcBuildBridge);
390 return;
393 /* only query bridge building possibility once, result is the same for all bridges!
394 * returns CMD_ERROR on failure, and price on success */
395 StringID errmsg = INVALID_STRING_ID;
396 CommandCost ret = DoCommand(end, start, type, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)) | DC_QUERY_COST, CMD_BUILD_BRIDGE);
398 GUIBridgeList *bl = NULL;
399 if (ret.Failed()) {
400 errmsg = ret.GetErrorMessage();
401 } else {
402 /* check which bridges can be built */
403 const uint tot_bridgedata_len = CalcBridgeLenCostFactor(bridge_len + 2);
405 bl = new GUIBridgeList();
407 Money infra_cost = 0;
408 switch (transport_type) {
409 case TRANSPORT_ROAD:
410 infra_cost = (bridge_len + 2) * _price[PR_BUILD_ROAD] * 2;
411 /* In case we add a new road type as well, we must be aware of those costs. */
412 if (IsBridgeTile(start)) infra_cost *= CountBits(GetRoadTypes(start) | (RoadTypes)road_rail_type);
413 break;
414 case TRANSPORT_RAIL: infra_cost = (bridge_len + 2) * RailBuildCost((RailType)road_rail_type); break;
415 default: break;
418 /* loop for all bridgetypes */
419 for (BridgeType brd_type = 0; brd_type != MAX_BRIDGES; brd_type++) {
420 if (CheckBridgeAvailability(brd_type, bridge_len).Succeeded()) {
421 /* bridge is accepted, add to list */
422 BuildBridgeData *item = bl->Append();
423 item->index = brd_type;
424 item->spec = GetBridgeSpec(brd_type);
425 /* Add to terraforming & bulldozing costs the cost of the
426 * bridge itself (not computed with DC_QUERY_COST) */
427 item->cost = ret.GetCost() + (((int64)tot_bridgedata_len * _price[PR_BUILD_BRIDGE] * item->spec->price) >> 8) + infra_cost;
432 if (bl != NULL && bl->Length() != 0) {
433 new BuildBridgeWindow(&_build_bridge_desc, start, end, type, bl);
434 } else {
435 delete bl;
436 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_BRIDGE_HERE, errmsg, WL_INFO, TileX(end) * TILE_SIZE, TileY(end) * TILE_SIZE);