build_vehicle_gui.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "engine_base.h"
00014 #include "engine_func.h"
00015 #include "station_base.h"
00016 #include "articulated_vehicles.h"
00017 #include "textbuf_gui.h"
00018 #include "command_func.h"
00019 #include "company_func.h"
00020 #include "vehicle_gui.h"
00021 #include "newgrf_engine.h"
00022 #include "newgrf_text.h"
00023 #include "group.h"
00024 #include "string_func.h"
00025 #include "strings_func.h"
00026 #include "window_func.h"
00027 #include "date_func.h"
00028 #include "vehicle_func.h"
00029 #include "widgets/dropdown_func.h"
00030 #include "engine_gui.h"
00031 #include "cargotype.h"
00032 #include "core/geometry_func.hpp"
00033 
00034 #include "widgets/build_vehicle_widget.h"
00035 
00036 #include "table/strings.h"
00037 
00043 uint GetEngineListHeight(VehicleType type)
00044 {
00045   return max<uint>(FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM, GetVehicleHeight(type));
00046 }
00047 
00048 static const NWidgetPart _nested_build_vehicle_widgets[] = {
00049   NWidget(NWID_HORIZONTAL),
00050     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00051     NWidget(WWT_CAPTION, COLOUR_GREY, WID_BV_CAPTION), SetDataTip(STR_WHITE_STRING, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00052     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00053     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00054   EndContainer(),
00055   NWidget(WWT_PANEL, COLOUR_GREY),
00056     NWidget(NWID_HORIZONTAL),
00057       NWidget(NWID_VERTICAL),
00058         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_SORT_ASSENDING_DESCENDING), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0),
00059         NWidget(NWID_SPACER), SetFill(1, 1),
00060       EndContainer(),
00061       NWidget(NWID_VERTICAL),
00062         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_BV_SORT_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
00063         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_BV_CARGO_FILTER_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_FILTER_CRITERIA),
00064       EndContainer(),
00065     EndContainer(),
00066   EndContainer(),
00067   /* Vehicle list. */
00068   NWidget(NWID_HORIZONTAL),
00069     NWidget(WWT_MATRIX, COLOUR_GREY, WID_BV_LIST), SetResize(1, 1), SetFill(1, 0), SetDataTip(0x101, STR_NULL), SetScrollbar(WID_BV_SCROLLBAR),
00070     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_BV_SCROLLBAR),
00071   EndContainer(),
00072   /* Panel with details. */
00073   NWidget(WWT_PANEL, COLOUR_GREY, WID_BV_PANEL), SetMinimalSize(240, 122), SetResize(1, 0), EndContainer(),
00074   /* Build/rename buttons, resize button. */
00075   NWidget(NWID_HORIZONTAL),
00076     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_BV_BUILD_SEL),
00077       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_BUILD), SetResize(1, 0), SetFill(1, 0),
00078     EndContainer(),
00079     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_RENAME), SetResize(1, 0), SetFill(1, 0),
00080     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00081   EndContainer(),
00082 };
00083 
00085 static const CargoID CF_ANY  = CT_NO_REFIT; 
00086 static const CargoID CF_NONE = CT_INVALID;  
00087 
00088 static bool _internal_sort_order;           
00089 static byte _last_sort_criteria[]      = {0, 0, 0, 0};
00090 static bool _last_sort_order[]         = {false, false, false, false};
00091 static CargoID _last_filter_criteria[] = {CF_ANY, CF_ANY, CF_ANY, CF_ANY};
00092 
00099 static int CDECL EngineNumberSorter(const EngineID *a, const EngineID *b)
00100 {
00101   int r = ListPositionOfEngine(*a) - ListPositionOfEngine(*b);
00102 
00103   return _internal_sort_order ? -r : r;
00104 }
00105 
00112 static int CDECL EngineIntroDateSorter(const EngineID *a, const EngineID *b)
00113 {
00114   const int va = Engine::Get(*a)->intro_date;
00115   const int vb = Engine::Get(*b)->intro_date;
00116   const int r = va - vb;
00117 
00118   /* Use EngineID to sort instead since we want consistent sorting */
00119   if (r == 0) return EngineNumberSorter(a, b);
00120   return _internal_sort_order ? -r : r;
00121 }
00122 
00129 static int CDECL EngineNameSorter(const EngineID *a, const EngineID *b)
00130 {
00131   static EngineID last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE };
00132   static char     last_name[2][64] = { "\0", "\0" };
00133 
00134   const EngineID va = *a;
00135   const EngineID vb = *b;
00136 
00137   if (va != last_engine[0]) {
00138     last_engine[0] = va;
00139     SetDParam(0, va);
00140     GetString(last_name[0], STR_ENGINE_NAME, lastof(last_name[0]));
00141   }
00142 
00143   if (vb != last_engine[1]) {
00144     last_engine[1] = vb;
00145     SetDParam(0, vb);
00146     GetString(last_name[1], STR_ENGINE_NAME, lastof(last_name[1]));
00147   }
00148 
00149   int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
00150 
00151   /* Use EngineID to sort instead since we want consistent sorting */
00152   if (r == 0) return EngineNumberSorter(a, b);
00153   return _internal_sort_order ? -r : r;
00154 }
00155 
00162 static int CDECL EngineReliabilitySorter(const EngineID *a, const EngineID *b)
00163 {
00164   const int va = Engine::Get(*a)->reliability;
00165   const int vb = Engine::Get(*b)->reliability;
00166   const int r = va - vb;
00167 
00168   /* Use EngineID to sort instead since we want consistent sorting */
00169   if (r == 0) return EngineNumberSorter(a, b);
00170   return _internal_sort_order ? -r : r;
00171 }
00172 
00179 static int CDECL EngineCostSorter(const EngineID *a, const EngineID *b)
00180 {
00181   Money va = Engine::Get(*a)->GetCost();
00182   Money vb = Engine::Get(*b)->GetCost();
00183   int r = ClampToI32(va - vb);
00184 
00185   /* Use EngineID to sort instead since we want consistent sorting */
00186   if (r == 0) return EngineNumberSorter(a, b);
00187   return _internal_sort_order ? -r : r;
00188 }
00189 
00196 static int CDECL EngineSpeedSorter(const EngineID *a, const EngineID *b)
00197 {
00198   int va = Engine::Get(*a)->GetDisplayMaxSpeed();
00199   int vb = Engine::Get(*b)->GetDisplayMaxSpeed();
00200   int r = va - vb;
00201 
00202   /* Use EngineID to sort instead since we want consistent sorting */
00203   if (r == 0) return EngineNumberSorter(a, b);
00204   return _internal_sort_order ? -r : r;
00205 }
00206 
00213 static int CDECL EnginePowerSorter(const EngineID *a, const EngineID *b)
00214 {
00215   int va = Engine::Get(*a)->GetPower();
00216   int vb = Engine::Get(*b)->GetPower();
00217   int r = va - vb;
00218 
00219   /* Use EngineID to sort instead since we want consistent sorting */
00220   if (r == 0) return EngineNumberSorter(a, b);
00221   return _internal_sort_order ? -r : r;
00222 }
00223 
00230 static int CDECL EngineTractiveEffortSorter(const EngineID *a, const EngineID *b)
00231 {
00232   int va = Engine::Get(*a)->GetDisplayMaxTractiveEffort();
00233   int vb = Engine::Get(*b)->GetDisplayMaxTractiveEffort();
00234   int r = va - vb;
00235 
00236   /* Use EngineID to sort instead since we want consistent sorting */
00237   if (r == 0) return EngineNumberSorter(a, b);
00238   return _internal_sort_order ? -r : r;
00239 }
00240 
00247 static int CDECL EngineRunningCostSorter(const EngineID *a, const EngineID *b)
00248 {
00249   Money va = Engine::Get(*a)->GetRunningCost();
00250   Money vb = Engine::Get(*b)->GetRunningCost();
00251   int r = ClampToI32(va - vb);
00252 
00253   /* Use EngineID to sort instead since we want consistent sorting */
00254   if (r == 0) return EngineNumberSorter(a, b);
00255   return _internal_sort_order ? -r : r;
00256 }
00257 
00264 static int CDECL EnginePowerVsRunningCostSorter(const EngineID *a, const EngineID *b)
00265 {
00266   const Engine *e_a = Engine::Get(*a);
00267   const Engine *e_b = Engine::Get(*b);
00268 
00269   /* Here we are using a few tricks to get the right sort.
00270    * We want power/running cost, but since we usually got higher running cost than power and we store the result in an int,
00271    * we will actually calculate cunning cost/power (to make it more than 1).
00272    * Because of this, the return value have to be reversed as well and we return b - a instead of a - b.
00273    * Another thing is that both power and running costs should be doubled for multiheaded engines.
00274    * Since it would be multipling with 2 in both numerator and denumerator, it will even themselves out and we skip checking for multiheaded. */
00275   Money va = (e_a->GetRunningCost()) / max(1U, (uint)e_a->GetPower());
00276   Money vb = (e_b->GetRunningCost()) / max(1U, (uint)e_b->GetPower());
00277   int r = ClampToI32(vb - va);
00278 
00279   /* Use EngineID to sort instead since we want consistent sorting */
00280   if (r == 0) return EngineNumberSorter(a, b);
00281   return _internal_sort_order ? -r : r;
00282 }
00283 
00284 /* Train sorting functions */
00285 
00292 static int CDECL TrainEngineCapacitySorter(const EngineID *a, const EngineID *b)
00293 {
00294   const RailVehicleInfo *rvi_a = RailVehInfo(*a);
00295   const RailVehicleInfo *rvi_b = RailVehInfo(*b);
00296 
00297   int va = GetTotalCapacityOfArticulatedParts(*a) * (rvi_a->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
00298   int vb = GetTotalCapacityOfArticulatedParts(*b) * (rvi_b->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
00299   int r = va - vb;
00300 
00301   /* Use EngineID to sort instead since we want consistent sorting */
00302   if (r == 0) return EngineNumberSorter(a, b);
00303   return _internal_sort_order ? -r : r;
00304 }
00305 
00312 static int CDECL TrainEnginesThenWagonsSorter(const EngineID *a, const EngineID *b)
00313 {
00314   int val_a = (RailVehInfo(*a)->railveh_type == RAILVEH_WAGON ? 1 : 0);
00315   int val_b = (RailVehInfo(*b)->railveh_type == RAILVEH_WAGON ? 1 : 0);
00316   int r = val_a - val_b;
00317 
00318   /* Use EngineID to sort instead since we want consistent sorting */
00319   if (r == 0) return EngineNumberSorter(a, b);
00320   return _internal_sort_order ? -r : r;
00321 }
00322 
00323 /* Road vehicle sorting functions */
00324 
00331 static int CDECL RoadVehEngineCapacitySorter(const EngineID *a, const EngineID *b)
00332 {
00333   int va = GetTotalCapacityOfArticulatedParts(*a);
00334   int vb = GetTotalCapacityOfArticulatedParts(*b);
00335   int r = va - vb;
00336 
00337   /* Use EngineID to sort instead since we want consistent sorting */
00338   if (r == 0) return EngineNumberSorter(a, b);
00339   return _internal_sort_order ? -r : r;
00340 }
00341 
00342 /* Ship vehicle sorting functions */
00343 
00350 static int CDECL ShipEngineCapacitySorter(const EngineID *a, const EngineID *b)
00351 {
00352   const Engine *e_a = Engine::Get(*a);
00353   const Engine *e_b = Engine::Get(*b);
00354 
00355   int va = e_a->GetDisplayDefaultCapacity();
00356   int vb = e_b->GetDisplayDefaultCapacity();
00357   int r = va - vb;
00358 
00359   /* Use EngineID to sort instead since we want consistent sorting */
00360   if (r == 0) return EngineNumberSorter(a, b);
00361   return _internal_sort_order ? -r : r;
00362 }
00363 
00364 /* Aircraft sorting functions */
00365 
00372 static int CDECL AircraftEngineCargoSorter(const EngineID *a, const EngineID *b)
00373 {
00374   const Engine *e_a = Engine::Get(*a);
00375   const Engine *e_b = Engine::Get(*b);
00376 
00377   uint16 mail_a, mail_b;
00378   int va = e_a->GetDisplayDefaultCapacity(&mail_a);
00379   int vb = e_b->GetDisplayDefaultCapacity(&mail_b);
00380   int r = va - vb;
00381 
00382   if (r == 0) {
00383     /* The planes have the same passenger capacity. Check mail capacity instead */
00384     r = mail_a - mail_b;
00385 
00386     if (r == 0) {
00387       /* Use EngineID to sort instead since we want consistent sorting */
00388       return EngineNumberSorter(a, b);
00389     }
00390   }
00391   return _internal_sort_order ? -r : r;
00392 }
00393 
00400 static int CDECL AircraftRangeSorter(const EngineID *a, const EngineID *b)
00401 {
00402   uint16 r_a = Engine::Get(*a)->GetRange();
00403   uint16 r_b = Engine::Get(*b)->GetRange();
00404 
00405   int r = r_a - r_b;
00406 
00407   /* Use EngineID to sort instead since we want consistent sorting */
00408   if (r == 0) return EngineNumberSorter(a, b);
00409   return _internal_sort_order ? -r : r;
00410 }
00411 
00412 static EngList_SortTypeFunction * const _sorter[][11] = {{
00413   /* Trains */
00414   &EngineNumberSorter,
00415   &EngineCostSorter,
00416   &EngineSpeedSorter,
00417   &EnginePowerSorter,
00418   &EngineTractiveEffortSorter,
00419   &EngineIntroDateSorter,
00420   &EngineNameSorter,
00421   &EngineRunningCostSorter,
00422   &EnginePowerVsRunningCostSorter,
00423   &EngineReliabilitySorter,
00424   &TrainEngineCapacitySorter,
00425 }, {
00426   /* Road vehicles */
00427   &EngineNumberSorter,
00428   &EngineCostSorter,
00429   &EngineSpeedSorter,
00430   &EnginePowerSorter,
00431   &EngineTractiveEffortSorter,
00432   &EngineIntroDateSorter,
00433   &EngineNameSorter,
00434   &EngineRunningCostSorter,
00435   &EnginePowerVsRunningCostSorter,
00436   &EngineReliabilitySorter,
00437   &RoadVehEngineCapacitySorter,
00438 }, {
00439   /* Ships */
00440   &EngineNumberSorter,
00441   &EngineCostSorter,
00442   &EngineSpeedSorter,
00443   &EngineIntroDateSorter,
00444   &EngineNameSorter,
00445   &EngineRunningCostSorter,
00446   &EngineReliabilitySorter,
00447   &ShipEngineCapacitySorter,
00448 }, {
00449   /* Aircraft */
00450   &EngineNumberSorter,
00451   &EngineCostSorter,
00452   &EngineSpeedSorter,
00453   &EngineIntroDateSorter,
00454   &EngineNameSorter,
00455   &EngineRunningCostSorter,
00456   &EngineReliabilitySorter,
00457   &AircraftEngineCargoSorter,
00458   &AircraftRangeSorter,
00459 }};
00460 
00461 static const StringID _sort_listing[][12] = {{
00462   /* Trains */
00463   STR_SORT_BY_ENGINE_ID,
00464   STR_SORT_BY_COST,
00465   STR_SORT_BY_MAX_SPEED,
00466   STR_SORT_BY_POWER,
00467   STR_SORT_BY_TRACTIVE_EFFORT,
00468   STR_SORT_BY_INTRO_DATE,
00469   STR_SORT_BY_NAME,
00470   STR_SORT_BY_RUNNING_COST,
00471   STR_SORT_BY_POWER_VS_RUNNING_COST,
00472   STR_SORT_BY_RELIABILITY,
00473   STR_SORT_BY_CARGO_CAPACITY,
00474   INVALID_STRING_ID
00475 }, {
00476   /* Road vehicles */
00477   STR_SORT_BY_ENGINE_ID,
00478   STR_SORT_BY_COST,
00479   STR_SORT_BY_MAX_SPEED,
00480   STR_SORT_BY_POWER,
00481   STR_SORT_BY_TRACTIVE_EFFORT,
00482   STR_SORT_BY_INTRO_DATE,
00483   STR_SORT_BY_NAME,
00484   STR_SORT_BY_RUNNING_COST,
00485   STR_SORT_BY_POWER_VS_RUNNING_COST,
00486   STR_SORT_BY_RELIABILITY,
00487   STR_SORT_BY_CARGO_CAPACITY,
00488   INVALID_STRING_ID
00489 }, {
00490   /* Ships */
00491   STR_SORT_BY_ENGINE_ID,
00492   STR_SORT_BY_COST,
00493   STR_SORT_BY_MAX_SPEED,
00494   STR_SORT_BY_INTRO_DATE,
00495   STR_SORT_BY_NAME,
00496   STR_SORT_BY_RUNNING_COST,
00497   STR_SORT_BY_RELIABILITY,
00498   STR_SORT_BY_CARGO_CAPACITY,
00499   INVALID_STRING_ID
00500 }, {
00501   /* Aircraft */
00502   STR_SORT_BY_ENGINE_ID,
00503   STR_SORT_BY_COST,
00504   STR_SORT_BY_MAX_SPEED,
00505   STR_SORT_BY_INTRO_DATE,
00506   STR_SORT_BY_NAME,
00507   STR_SORT_BY_RUNNING_COST,
00508   STR_SORT_BY_RELIABILITY,
00509   STR_SORT_BY_CARGO_CAPACITY,
00510   STR_SORT_BY_RANGE,
00511   INVALID_STRING_ID
00512 }};
00513 
00515 static bool CDECL CargoFilter(const EngineID *eid, const CargoID cid)
00516 {
00517   if (cid == CF_ANY) return true;
00518   uint32 refit_mask = GetUnionOfArticulatedRefitMasks(*eid, true);
00519   return (cid == CF_NONE ? refit_mask == 0 : HasBit(refit_mask, cid));
00520 }
00521 
00522 static GUIEngineList::FilterFunction * const _filter_funcs[] = {
00523   &CargoFilter,
00524 };
00525 
00526 static int DrawCargoCapacityInfo(int left, int right, int y, EngineID engine, bool refittable)
00527 {
00528   CargoArray cap = GetCapacityOfArticulatedParts(engine);
00529 
00530   for (CargoID c = 0; c < NUM_CARGO; c++) {
00531     if (cap[c] == 0) continue;
00532 
00533     SetDParam(0, c);
00534     SetDParam(1, cap[c]);
00535     SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
00536     DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
00537     y += FONT_HEIGHT_NORMAL;
00538 
00539     /* Only show as refittable once */
00540     refittable = false;
00541   }
00542 
00543   return y;
00544 }
00545 
00546 /* Draw rail wagon specific details */
00547 static int DrawRailWagonPurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi)
00548 {
00549   const Engine *e = Engine::Get(engine_number);
00550 
00551   /* Purchase cost */
00552   SetDParam(0, e->GetCost());
00553   DrawString(left, right, y, STR_PURCHASE_INFO_COST);
00554   y += FONT_HEIGHT_NORMAL;
00555 
00556   /* Wagon weight - (including cargo) */
00557   uint weight = e->GetDisplayWeight();
00558   SetDParam(0, weight);
00559   uint cargo_weight = (e->CanCarryCargo() ? CargoSpec::Get(e->GetDefaultCargoType())->weight * GetTotalCapacityOfArticulatedParts(engine_number) / 16 : 0);
00560   SetDParam(1, cargo_weight + weight);
00561   DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT);
00562   y += FONT_HEIGHT_NORMAL;
00563 
00564   /* Wagon speed limit, displayed if above zero */
00565   if (_settings_game.vehicle.wagon_speed_limits) {
00566     uint max_speed = e->GetDisplayMaxSpeed();
00567     if (max_speed > 0) {
00568       SetDParam(0, max_speed);
00569       DrawString(left, right, y, STR_PURCHASE_INFO_SPEED);
00570       y += FONT_HEIGHT_NORMAL;
00571     }
00572   }
00573 
00574   /* Running cost */
00575   if (rvi->running_cost_class != INVALID_PRICE) {
00576     SetDParam(0, e->GetRunningCost());
00577     DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
00578     y += FONT_HEIGHT_NORMAL;
00579   }
00580 
00581   return y;
00582 }
00583 
00584 /* Draw locomotive specific details */
00585 static int DrawRailEnginePurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi)
00586 {
00587   const Engine *e = Engine::Get(engine_number);
00588 
00589   /* Purchase Cost - Engine weight */
00590   SetDParam(0, e->GetCost());
00591   SetDParam(1, e->GetDisplayWeight());
00592   DrawString(left, right, y, STR_PURCHASE_INFO_COST_WEIGHT);
00593   y += FONT_HEIGHT_NORMAL;
00594 
00595   /* Max speed - Engine power */
00596   SetDParam(0, e->GetDisplayMaxSpeed());
00597   SetDParam(1, e->GetPower());
00598   DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER);
00599   y += FONT_HEIGHT_NORMAL;
00600 
00601   /* Max tractive effort - not applicable if old acceleration or maglev */
00602   if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && GetRailTypeInfo(rvi->railtype)->acceleration_type != 2) {
00603     SetDParam(0, e->GetDisplayMaxTractiveEffort());
00604     DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE);
00605     y += FONT_HEIGHT_NORMAL;
00606   }
00607 
00608   /* Running cost */
00609   if (rvi->running_cost_class != INVALID_PRICE) {
00610     SetDParam(0, e->GetRunningCost());
00611     DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
00612     y += FONT_HEIGHT_NORMAL;
00613   }
00614 
00615   /* Powered wagons power - Powered wagons extra weight */
00616   if (rvi->pow_wag_power != 0) {
00617     SetDParam(0, rvi->pow_wag_power);
00618     SetDParam(1, rvi->pow_wag_weight);
00619     DrawString(left, right, y, STR_PURCHASE_INFO_PWAGPOWER_PWAGWEIGHT);
00620     y += FONT_HEIGHT_NORMAL;
00621   }
00622 
00623   return y;
00624 }
00625 
00626 /* Draw road vehicle specific details */
00627 static int DrawRoadVehPurchaseInfo(int left, int right, int y, EngineID engine_number)
00628 {
00629   const Engine *e = Engine::Get(engine_number);
00630 
00631   if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
00632     /* Purchase Cost */
00633     SetDParam(0, e->GetCost());
00634     DrawString(left, right, y, STR_PURCHASE_INFO_COST);
00635     y += FONT_HEIGHT_NORMAL;
00636 
00637     /* Road vehicle weight - (including cargo) */
00638     int16 weight = e->GetDisplayWeight();
00639     SetDParam(0, weight);
00640     uint cargo_weight = (e->CanCarryCargo() ? CargoSpec::Get(e->GetDefaultCargoType())->weight * GetTotalCapacityOfArticulatedParts(engine_number) / 16 : 0);
00641     SetDParam(1, cargo_weight + weight);
00642     DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT);
00643     y += FONT_HEIGHT_NORMAL;
00644 
00645     /* Max speed - Engine power */
00646     SetDParam(0, e->GetDisplayMaxSpeed());
00647     SetDParam(1, e->GetPower());
00648     DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER);
00649     y += FONT_HEIGHT_NORMAL;
00650 
00651     /* Max tractive effort */
00652     SetDParam(0, e->GetDisplayMaxTractiveEffort());
00653     DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE);
00654     y += FONT_HEIGHT_NORMAL;
00655   } else {
00656     /* Purchase cost - Max speed */
00657     SetDParam(0, e->GetCost());
00658     SetDParam(1, e->GetDisplayMaxSpeed());
00659     DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
00660     y += FONT_HEIGHT_NORMAL;
00661   }
00662 
00663   /* Running cost */
00664   SetDParam(0, e->GetRunningCost());
00665   DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
00666   y += FONT_HEIGHT_NORMAL;
00667 
00668   return y;
00669 }
00670 
00671 /* Draw ship specific details */
00672 static int DrawShipPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable)
00673 {
00674   const Engine *e = Engine::Get(engine_number);
00675 
00676   /* Purchase cost - Max speed */
00677   uint raw_speed = e->GetDisplayMaxSpeed();
00678   uint ocean_speed = e->u.ship.ApplyWaterClassSpeedFrac(raw_speed, true);
00679   uint canal_speed = e->u.ship.ApplyWaterClassSpeedFrac(raw_speed, false);
00680 
00681   SetDParam(0, e->GetCost());
00682   if (ocean_speed == canal_speed) {
00683     SetDParam(1, ocean_speed);
00684     DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
00685     y += FONT_HEIGHT_NORMAL;
00686   } else {
00687     DrawString(left, right, y, STR_PURCHASE_INFO_COST);
00688     y += FONT_HEIGHT_NORMAL;
00689 
00690     SetDParam(0, ocean_speed);
00691     DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_OCEAN);
00692     y += FONT_HEIGHT_NORMAL;
00693 
00694     SetDParam(0, canal_speed);
00695     DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_CANAL);
00696     y += FONT_HEIGHT_NORMAL;
00697   }
00698 
00699   /* Cargo type + capacity */
00700   SetDParam(0, e->GetDefaultCargoType());
00701   SetDParam(1, e->GetDisplayDefaultCapacity());
00702   SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
00703   DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
00704   y += FONT_HEIGHT_NORMAL;
00705 
00706   /* Running cost */
00707   SetDParam(0, e->GetRunningCost());
00708   DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
00709   y += FONT_HEIGHT_NORMAL;
00710 
00711   return y;
00712 }
00713 
00714 /* Draw aircraft specific details */
00715 static int DrawAircraftPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable)
00716 {
00717   const Engine *e = Engine::Get(engine_number);
00718   CargoID cargo = e->GetDefaultCargoType();
00719 
00720   /* Purchase cost - Max speed */
00721   SetDParam(0, e->GetCost());
00722   SetDParam(1, e->GetDisplayMaxSpeed());
00723   DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
00724   y += FONT_HEIGHT_NORMAL;
00725 
00726   /* Cargo capacity */
00727   uint16 mail_capacity;
00728   uint capacity = e->GetDisplayDefaultCapacity(&mail_capacity);
00729   if (mail_capacity > 0) {
00730     SetDParam(0, cargo);
00731     SetDParam(1, capacity);
00732     SetDParam(2, CT_MAIL);
00733     SetDParam(3, mail_capacity);
00734     DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_CAPACITY);
00735   } else {
00736     /* Note, if the default capacity is selected by the refit capacity
00737      * callback, then the capacity shown is likely to be incorrect. */
00738     SetDParam(0, cargo);
00739     SetDParam(1, capacity);
00740     SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
00741     DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
00742   }
00743   y += FONT_HEIGHT_NORMAL;
00744 
00745   /* Running cost */
00746   SetDParam(0, e->GetRunningCost());
00747   DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
00748   y += FONT_HEIGHT_NORMAL;
00749 
00750   uint16 range = e->GetRange();
00751   if (range != 0) {
00752     SetDParam(0, range);
00753     DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_RANGE);
00754     y += FONT_HEIGHT_NORMAL;
00755   }
00756 
00757   return y;
00758 }
00759 
00768 static uint ShowAdditionalText(int left, int right, int y, EngineID engine)
00769 {
00770   uint16 callback = GetVehicleCallback(CBID_VEHICLE_ADDITIONAL_TEXT, 0, 0, engine, NULL);
00771   if (callback == CALLBACK_FAILED || callback == 0x400) return y;
00772   if (callback > 0x400) {
00773     ErrorUnknownCallbackResult(Engine::Get(engine)->GetGRFID(), CBID_VEHICLE_ADDITIONAL_TEXT, callback);
00774     return y;
00775   }
00776 
00777   StartTextRefStackUsage(6);
00778   uint result = DrawStringMultiLine(left, right, y, INT32_MAX, GetGRFStringID(Engine::Get(engine)->GetGRFID(), 0xD000 + callback), TC_BLACK);
00779   StopTextRefStackUsage();
00780   return result;
00781 }
00782 
00789 int DrawVehiclePurchaseInfo(int left, int right, int y, EngineID engine_number)
00790 {
00791   const Engine *e = Engine::Get(engine_number);
00792   YearMonthDay ymd;
00793   ConvertDateToYMD(e->intro_date, &ymd);
00794   bool refittable = IsArticulatedVehicleRefittable(engine_number);
00795   bool articulated_cargo = false;
00796 
00797   switch (e->type) {
00798     default: NOT_REACHED();
00799     case VEH_TRAIN:
00800       if (e->u.rail.railveh_type == RAILVEH_WAGON) {
00801         y = DrawRailWagonPurchaseInfo(left, right, y, engine_number, &e->u.rail);
00802       } else {
00803         y = DrawRailEnginePurchaseInfo(left, right, y, engine_number, &e->u.rail);
00804       }
00805       articulated_cargo = true;
00806       break;
00807 
00808     case VEH_ROAD:
00809       y = DrawRoadVehPurchaseInfo(left, right, y, engine_number);
00810       articulated_cargo = true;
00811       break;
00812 
00813     case VEH_SHIP:
00814       y = DrawShipPurchaseInfo(left, right, y, engine_number, refittable);
00815       break;
00816 
00817     case VEH_AIRCRAFT:
00818       y = DrawAircraftPurchaseInfo(left, right, y, engine_number, refittable);
00819       break;
00820   }
00821 
00822   if (articulated_cargo) {
00823     /* Cargo type + capacity, or N/A */
00824     int new_y = DrawCargoCapacityInfo(left, right, y, engine_number, refittable);
00825 
00826     if (new_y == y) {
00827       SetDParam(0, CT_INVALID);
00828       SetDParam(2, STR_EMPTY);
00829       DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
00830       y += FONT_HEIGHT_NORMAL;
00831     } else {
00832       y = new_y;
00833     }
00834   }
00835 
00836   /* Draw details that apply to all types except rail wagons. */
00837   if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
00838     /* Design date - Life length */
00839     SetDParam(0, ymd.year);
00840     SetDParam(1, e->GetLifeLengthInDays() / DAYS_IN_LEAP_YEAR);
00841     DrawString(left, right, y, STR_PURCHASE_INFO_DESIGNED_LIFE);
00842     y += FONT_HEIGHT_NORMAL;
00843 
00844     /* Reliability */
00845     SetDParam(0, ToPercent16(e->reliability));
00846     DrawString(left, right, y, STR_PURCHASE_INFO_RELIABILITY);
00847     y += FONT_HEIGHT_NORMAL;
00848   }
00849 
00850   /* Additional text from NewGRF */
00851   y = ShowAdditionalText(left, right, y, engine_number);
00852   if (refittable) y = ShowRefitOptionsList(left, right, y, engine_number);
00853 
00854   return y;
00855 }
00856 
00870 void DrawEngineList(VehicleType type, int l, int r, int y, const GUIEngineList *eng_list, uint16 min, uint16 max, EngineID selected_id, bool show_count, GroupID selected_group)
00871 {
00872   static const int sprite_widths[]  = { 60, 60, 76, 67 };
00873   static const int sprite_y_offsets[] = { -1, -1, -2, -2 };
00874 
00875   /* Obligatory sanity checks! */
00876   assert((uint)type < lengthof(sprite_widths));
00877   assert_compile(lengthof(sprite_y_offsets) == lengthof(sprite_widths));
00878   assert(max <= eng_list->Length());
00879 
00880   bool rtl = _current_text_dir == TD_RTL;
00881   int step_size = GetEngineListHeight(type);
00882   int sprite_width = sprite_widths[type];
00883 
00884   int sprite_x        = (rtl ? r - sprite_width / 2 : l + sprite_width / 2) - 1;
00885   int sprite_y_offset = sprite_y_offsets[type] + step_size / 2;
00886 
00887   int text_left  = l + (rtl ? WD_FRAMERECT_LEFT : sprite_width);
00888   int text_right = r - (rtl ? sprite_width : WD_FRAMERECT_RIGHT);
00889 
00890   int normal_text_y_offset = (step_size - FONT_HEIGHT_NORMAL) / 2;
00891   int small_text_y_offset  = step_size - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1;
00892 
00893   for (; min < max; min++, y += step_size) {
00894     const EngineID engine = (*eng_list)[min];
00895     /* Note: num_engines is only used in the autoreplace GUI, so it is correct to use _local_company here. */
00896     const uint num_engines = GetGroupNumEngines(_local_company, selected_group, engine);
00897 
00898     SetDParam(0, engine);
00899     DrawString(text_left, text_right, y + normal_text_y_offset, STR_ENGINE_NAME, engine == selected_id ? TC_WHITE : TC_BLACK);
00900     DrawVehicleEngine(l, r, sprite_x, y + sprite_y_offset, engine, (show_count && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(engine, _local_company), EIT_PURCHASE);
00901     if (show_count) {
00902       SetDParam(0, num_engines);
00903       DrawString(text_left, text_right, y + small_text_y_offset, STR_TINY_BLACK_COMA, TC_FROMSTRING, SA_RIGHT);
00904     }
00905   }
00906 }
00907 
00908 
00909 struct BuildVehicleWindow : Window {
00910   VehicleType vehicle_type;
00911   union {
00912     RailTypeByte railtype;
00913     RoadTypes roadtypes;
00914   } filter;
00915   bool descending_sort_order;
00916   byte sort_criteria;
00917   bool listview_mode;
00918   EngineID sel_engine;
00919   EngineID rename_engine;
00920   GUIEngineList eng_list;
00921   CargoID cargo_filter[NUM_CARGO + 2];        
00922   StringID cargo_filter_texts[NUM_CARGO + 3]; 
00923   byte cargo_filter_criteria;                 
00924   int details_height;                         
00925   Scrollbar *vscroll;
00926 
00927   BuildVehicleWindow(const WindowDesc *desc, TileIndex tile, VehicleType type) : Window()
00928   {
00929     this->vehicle_type = type;
00930     this->window_number = tile == INVALID_TILE ? (int)type : tile;
00931 
00932     this->sel_engine      = INVALID_ENGINE;
00933 
00934     this->sort_criteria         = _last_sort_criteria[type];
00935     this->descending_sort_order = _last_sort_order[type];
00936 
00937     switch (type) {
00938       default: NOT_REACHED();
00939       case VEH_TRAIN:
00940         this->filter.railtype = (tile == INVALID_TILE) ? RAILTYPE_END : GetRailType(tile);
00941         break;
00942       case VEH_ROAD:
00943         this->filter.roadtypes = (tile == INVALID_TILE) ? ROADTYPES_ALL : GetRoadTypes(tile);
00944       case VEH_SHIP:
00945       case VEH_AIRCRAFT:
00946         break;
00947     }
00948 
00949     this->listview_mode = (this->window_number <= VEH_END);
00950 
00951     this->CreateNestedTree(desc);
00952 
00953     this->vscroll = this->GetScrollbar(WID_BV_SCROLLBAR);
00954 
00955     /* If we are just viewing the list of vehicles, we do not need the Build button.
00956      * So we just hide it, and enlarge the Rename buton by the now vacant place. */
00957     if (this->listview_mode) this->GetWidget<NWidgetStacked>(WID_BV_BUILD_SEL)->SetDisplayedPlane(SZSP_NONE);
00958 
00959     NWidgetCore *widget = this->GetWidget<NWidgetCore>(WID_BV_LIST);
00960     widget->tool_tip = STR_BUY_VEHICLE_TRAIN_LIST_TOOLTIP + type;
00961 
00962     widget = this->GetWidget<NWidgetCore>(WID_BV_BUILD);
00963     widget->widget_data = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_BUTTON + type;
00964     widget->tool_tip    = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_TOOLTIP + type;
00965 
00966     widget = this->GetWidget<NWidgetCore>(WID_BV_RENAME);
00967     widget->widget_data = STR_BUY_VEHICLE_TRAIN_RENAME_BUTTON + type;
00968     widget->tool_tip    = STR_BUY_VEHICLE_TRAIN_RENAME_TOOLTIP + type;
00969 
00970     this->details_height = ((this->vehicle_type == VEH_TRAIN) ? 10 : 9) * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
00971 
00972     this->FinishInitNested(desc, tile == INVALID_TILE ? (int)type : tile);
00973 
00974     this->owner = (tile != INVALID_TILE) ? GetTileOwner(tile) : _local_company;
00975 
00976     this->eng_list.ForceRebuild();
00977     this->GenerateBuildList(); // generate the list, since we need it in the next line
00978     /* Select the first engine in the list as default when opening the window */
00979     if (this->eng_list.Length() > 0) this->sel_engine = this->eng_list[0];
00980   }
00981 
00983   void SetCargoFilterArray()
00984   {
00985     uint filter_items = 0;
00986 
00987     /* Add item for disabling filtering. */
00988     this->cargo_filter[filter_items] = CF_ANY;
00989     this->cargo_filter_texts[filter_items] = STR_PURCHASE_INFO_ALL_TYPES;
00990     filter_items++;
00991 
00992     /* Add item for vehicles not carrying anything, e.g. train engines.
00993      * This could also be useful for eyecandy vehicles of other types, but is likely too confusing for joe, */
00994     if (this->vehicle_type == VEH_TRAIN) {
00995       this->cargo_filter[filter_items] = CF_NONE;
00996       this->cargo_filter_texts[filter_items] = STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE;
00997       filter_items++;
00998     }
00999 
01000     /* Collect available cargo types for filtering. */
01001     const CargoSpec *cs;
01002     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
01003       this->cargo_filter[filter_items] = cs->Index();
01004       this->cargo_filter_texts[filter_items] = cs->name;
01005       filter_items++;
01006     }
01007 
01008     /* Terminate the filter list. */
01009     this->cargo_filter_texts[filter_items] = INVALID_STRING_ID;
01010 
01011     /* If not found, the cargo criteria will be set to all cargoes. */
01012     this->cargo_filter_criteria = 0;
01013 
01014     /* Find the last cargo filter criteria. */
01015     for (uint i = 0; i < filter_items; i++) {
01016       if (this->cargo_filter[i] == _last_filter_criteria[this->vehicle_type]) {
01017         this->cargo_filter_criteria = i;
01018         break;
01019       }
01020     }
01021 
01022     this->eng_list.SetFilterFuncs(_filter_funcs);
01023     this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
01024   }
01025 
01026   void OnInit()
01027   {
01028     this->SetCargoFilterArray();
01029   }
01030 
01032   void FilterEngineList()
01033   {
01034     this->eng_list.Filter(this->cargo_filter[this->cargo_filter_criteria]);
01035     if (0 == this->eng_list.Length()) { // no engine passed through the filter, invalidate the previously selected engine
01036       this->sel_engine = INVALID_ENGINE;
01037     } else if (!this->eng_list.Contains(this->sel_engine)) { // previously selected engine didn't pass the filter, select the first engine of the list
01038       this->sel_engine = this->eng_list[0];
01039     }
01040   }
01041 
01043   bool FilterSingleEngine(EngineID eid)
01044   {
01045     CargoID filter_type = this->cargo_filter[this->cargo_filter_criteria];
01046     return (filter_type == CF_ANY || CargoFilter(&eid, filter_type));
01047   }
01048 
01049   /* Figure out what train EngineIDs to put in the list */
01050   void GenerateBuildTrainList()
01051   {
01052     EngineID sel_id = INVALID_ENGINE;
01053     int num_engines = 0;
01054     int num_wagons  = 0;
01055 
01056     this->filter.railtype = (this->listview_mode) ? RAILTYPE_END : GetRailType(this->window_number);
01057 
01058     this->eng_list.Clear();
01059 
01060     /* Make list of all available train engines and wagons.
01061      * Also check to see if the previously selected engine is still available,
01062      * and if not, reset selection to INVALID_ENGINE. This could be the case
01063      * when engines become obsolete and are removed */
01064     const Engine *e;
01065     FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) {
01066       EngineID eid = e->index;
01067       const RailVehicleInfo *rvi = &e->u.rail;
01068 
01069       if (this->filter.railtype != RAILTYPE_END && !HasPowerOnRail(rvi->railtype, this->filter.railtype)) continue;
01070       if (!IsEngineBuildable(eid, VEH_TRAIN, _local_company)) continue;
01071 
01072       /* Filter now! So num_engines and num_wagons is valid */
01073       if (!FilterSingleEngine(eid)) continue;
01074 
01075       *this->eng_list.Append() = eid;
01076 
01077       if (rvi->railveh_type != RAILVEH_WAGON) {
01078         num_engines++;
01079       } else {
01080         num_wagons++;
01081       }
01082 
01083       if (eid == this->sel_engine) sel_id = eid;
01084     }
01085 
01086     this->sel_engine = sel_id;
01087 
01088     /* make engines first, and then wagons, sorted by ListPositionOfEngine() */
01089     _internal_sort_order = false;
01090     EngList_Sort(&this->eng_list, TrainEnginesThenWagonsSorter);
01091 
01092     /* and then sort engines */
01093     _internal_sort_order = this->descending_sort_order;
01094     EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], 0, num_engines);
01095 
01096     /* and finally sort wagons */
01097     EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], num_engines, num_wagons);
01098   }
01099 
01100   /* Figure out what road vehicle EngineIDs to put in the list */
01101   void GenerateBuildRoadVehList()
01102   {
01103     EngineID sel_id = INVALID_ENGINE;
01104 
01105     this->eng_list.Clear();
01106 
01107     const Engine *e;
01108     FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) {
01109       EngineID eid = e->index;
01110       if (!IsEngineBuildable(eid, VEH_ROAD, _local_company)) continue;
01111       if (!HasBit(this->filter.roadtypes, HasBit(EngInfo(eid)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD)) continue;
01112       *this->eng_list.Append() = eid;
01113 
01114       if (eid == this->sel_engine) sel_id = eid;
01115     }
01116     this->sel_engine = sel_id;
01117   }
01118 
01119   /* Figure out what ship EngineIDs to put in the list */
01120   void GenerateBuildShipList()
01121   {
01122     EngineID sel_id = INVALID_ENGINE;
01123     this->eng_list.Clear();
01124 
01125     const Engine *e;
01126     FOR_ALL_ENGINES_OF_TYPE(e, VEH_SHIP) {
01127       EngineID eid = e->index;
01128       if (!IsEngineBuildable(eid, VEH_SHIP, _local_company)) continue;
01129       *this->eng_list.Append() = eid;
01130 
01131       if (eid == this->sel_engine) sel_id = eid;
01132     }
01133     this->sel_engine = sel_id;
01134   }
01135 
01136   /* Figure out what aircraft EngineIDs to put in the list */
01137   void GenerateBuildAircraftList()
01138   {
01139     EngineID sel_id = INVALID_ENGINE;
01140 
01141     this->eng_list.Clear();
01142 
01143     const Station *st = this->listview_mode ? NULL : Station::GetByTile(this->window_number);
01144 
01145     /* Make list of all available planes.
01146      * Also check to see if the previously selected plane is still available,
01147      * and if not, reset selection to INVALID_ENGINE. This could be the case
01148      * when planes become obsolete and are removed */
01149     const Engine *e;
01150     FOR_ALL_ENGINES_OF_TYPE(e, VEH_AIRCRAFT) {
01151       EngineID eid = e->index;
01152       if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_company)) continue;
01153       /* First VEH_END window_numbers are fake to allow a window open for all different types at once */
01154       if (!this->listview_mode && !CanVehicleUseStation(eid, st)) continue;
01155 
01156       *this->eng_list.Append() = eid;
01157       if (eid == this->sel_engine) sel_id = eid;
01158     }
01159 
01160     this->sel_engine = sel_id;
01161   }
01162 
01163   /* Generate the list of vehicles */
01164   void GenerateBuildList()
01165   {
01166     if (!this->eng_list.NeedRebuild()) return;
01167     switch (this->vehicle_type) {
01168       default: NOT_REACHED();
01169       case VEH_TRAIN:
01170         this->GenerateBuildTrainList();
01171         this->eng_list.Compact();
01172         this->eng_list.RebuildDone();
01173         return; // trains should not reach the last sorting
01174       case VEH_ROAD:
01175         this->GenerateBuildRoadVehList();
01176         break;
01177       case VEH_SHIP:
01178         this->GenerateBuildShipList();
01179         break;
01180       case VEH_AIRCRAFT:
01181         this->GenerateBuildAircraftList();
01182         break;
01183     }
01184 
01185     this->FilterEngineList();
01186 
01187     _internal_sort_order = this->descending_sort_order;
01188     EngList_Sort(&this->eng_list, _sorter[this->vehicle_type][this->sort_criteria]);
01189 
01190     this->eng_list.Compact();
01191     this->eng_list.RebuildDone();
01192   }
01193 
01194   void OnClick(Point pt, int widget, int click_count)
01195   {
01196     switch (widget) {
01197       case WID_BV_SORT_ASSENDING_DESCENDING:
01198         this->descending_sort_order ^= true;
01199         _last_sort_order[this->vehicle_type] = this->descending_sort_order;
01200         this->eng_list.ForceRebuild();
01201         this->SetDirty();
01202         break;
01203 
01204       case WID_BV_LIST: {
01205         uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_BV_LIST);
01206         size_t num_items = this->eng_list.Length();
01207         this->sel_engine = (i < num_items) ? this->eng_list[i] : INVALID_ENGINE;
01208         this->SetDirty();
01209         if (click_count > 1 && !this->listview_mode) this->OnClick(pt, WID_BV_BUILD, 1);
01210         break;
01211       }
01212 
01213       case WID_BV_SORT_DROPDOWN: { // Select sorting criteria dropdown menu
01214         uint32 hidden_mask = 0;
01215         /* Disable sorting by power or tractive effort when the original acceleration model for road vehicles is being used. */
01216         if (this->vehicle_type == VEH_ROAD &&
01217             _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) {
01218           SetBit(hidden_mask, 3); // power
01219           SetBit(hidden_mask, 4); // tractive effort
01220           SetBit(hidden_mask, 8); // power by running costs
01221         }
01222         /* Disable sorting by tractive effort when the original acceleration model for trains is being used. */
01223         if (this->vehicle_type == VEH_TRAIN &&
01224             _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
01225           SetBit(hidden_mask, 4); // tractive effort
01226         }
01227         ShowDropDownMenu(this, _sort_listing[this->vehicle_type], this->sort_criteria, WID_BV_SORT_DROPDOWN, 0, hidden_mask);
01228         break;
01229       }
01230 
01231       case WID_BV_CARGO_FILTER_DROPDOWN: // Select cargo filtering criteria dropdown menu
01232         ShowDropDownMenu(this, this->cargo_filter_texts, this->cargo_filter_criteria, WID_BV_CARGO_FILTER_DROPDOWN, 0, 0);
01233         break;
01234 
01235       case WID_BV_BUILD: {
01236         EngineID sel_eng = this->sel_engine;
01237         if (sel_eng != INVALID_ENGINE) {
01238           CommandCallback *callback = (this->vehicle_type == VEH_TRAIN && RailVehInfo(sel_eng)->railveh_type == RAILVEH_WAGON) ? CcBuildWagon : CcBuildPrimaryVehicle;
01239           DoCommandP(this->window_number, sel_eng, 0, GetCmdBuildVeh(this->vehicle_type), callback);
01240         }
01241         break;
01242       }
01243 
01244       case WID_BV_RENAME: {
01245         EngineID sel_eng = this->sel_engine;
01246         if (sel_eng != INVALID_ENGINE) {
01247           this->rename_engine = sel_eng;
01248           SetDParam(0, sel_eng);
01249           ShowQueryString(STR_ENGINE_NAME, STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type, MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
01250         }
01251         break;
01252       }
01253     }
01254   }
01255 
01261   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01262   {
01263     if (!gui_scope) return;
01264     /* When switching to original acceleration model for road vehicles, clear the selected sort criteria if it is not available now. */
01265     if (this->vehicle_type == VEH_ROAD &&
01266         _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL &&
01267         this->sort_criteria > 7) {
01268       this->sort_criteria = 0;
01269       _last_sort_criteria[VEH_ROAD] = 0;
01270     }
01271     this->eng_list.ForceRebuild();
01272   }
01273 
01274   virtual void SetStringParameters(int widget) const
01275   {
01276     switch (widget) {
01277       case WID_BV_CAPTION:
01278         if (this->vehicle_type == VEH_TRAIN && !this->listview_mode) {
01279           const RailtypeInfo *rti = GetRailTypeInfo(this->filter.railtype);
01280           SetDParam(0, rti->strings.build_caption);
01281         } else {
01282           SetDParam(0, (this->listview_mode ? STR_VEHICLE_LIST_AVAILABLE_TRAINS : STR_BUY_VEHICLE_TRAIN_ALL_CAPTION) + this->vehicle_type);
01283         }
01284         break;
01285 
01286       case WID_BV_SORT_DROPDOWN:
01287         SetDParam(0, _sort_listing[this->vehicle_type][this->sort_criteria]);
01288         break;
01289 
01290       case WID_BV_CARGO_FILTER_DROPDOWN:
01291         SetDParam(0, this->cargo_filter_texts[this->cargo_filter_criteria]);
01292     }
01293   }
01294 
01295   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01296   {
01297     switch (widget) {
01298       case WID_BV_LIST:
01299         resize->height = GetEngineListHeight(this->vehicle_type);
01300         size->height = 3 * resize->height;
01301         break;
01302 
01303       case WID_BV_PANEL:
01304         size->height = this->details_height;
01305         break;
01306 
01307       case WID_BV_SORT_ASSENDING_DESCENDING: {
01308         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
01309         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
01310         d.height += padding.height;
01311         *size = maxdim(*size, d);
01312         break;
01313       }
01314     }
01315   }
01316 
01317   virtual void DrawWidget(const Rect &r, int widget) const
01318   {
01319     switch (widget) {
01320       case WID_BV_LIST:
01321         DrawEngineList(this->vehicle_type, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, &this->eng_list, this->vscroll->GetPosition(), min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->eng_list.Length()), this->sel_engine, false, DEFAULT_GROUP);
01322         break;
01323 
01324       case WID_BV_SORT_ASSENDING_DESCENDING:
01325         this->DrawSortButtonState(WID_BV_SORT_ASSENDING_DESCENDING, this->descending_sort_order ? SBS_DOWN : SBS_UP);
01326         break;
01327     }
01328   }
01329 
01330   virtual void OnPaint()
01331   {
01332     this->GenerateBuildList();
01333     this->vscroll->SetCount(this->eng_list.Length());
01334 
01335     this->DrawWidgets();
01336 
01337     if (!this->IsShaded()) {
01338       int needed_height = this->details_height;
01339       /* Draw details panels. */
01340       if (this->sel_engine != INVALID_ENGINE) {
01341         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_BV_PANEL);
01342         int text_end = DrawVehiclePurchaseInfo(nwi->pos_x + WD_FRAMETEXT_LEFT, nwi->pos_x + nwi->current_x - WD_FRAMETEXT_RIGHT,
01343             nwi->pos_y + WD_FRAMERECT_TOP, this->sel_engine);
01344         needed_height = max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM);
01345       }
01346       if (needed_height != this->details_height) { // Details window are not high enough, enlarge them.
01347         int resize = needed_height - this->details_height;
01348         this->details_height = needed_height;
01349         this->ReInit(0, resize);
01350         return;
01351       }
01352     }
01353   }
01354 
01355   virtual void OnQueryTextFinished(char *str)
01356   {
01357     if (str == NULL) return;
01358 
01359     DoCommandP(0, this->rename_engine, 0, CMD_RENAME_ENGINE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN_TYPE + this->vehicle_type), NULL, str);
01360   }
01361 
01362   virtual void OnDropdownSelect(int widget, int index)
01363   {
01364     switch (widget) {
01365       case WID_BV_SORT_DROPDOWN:
01366         if (this->sort_criteria != index) {
01367           this->sort_criteria = index;
01368           _last_sort_criteria[this->vehicle_type] = this->sort_criteria;
01369           this->eng_list.ForceRebuild();
01370         }
01371         break;
01372 
01373       case WID_BV_CARGO_FILTER_DROPDOWN: // Select a cargo filter criteria
01374         if (this->cargo_filter_criteria != index) {
01375           this->cargo_filter_criteria = index;
01376           _last_filter_criteria[this->vehicle_type] = this->cargo_filter[this->cargo_filter_criteria];
01377           /* deactivate filter if criteria is 'Show All', activate it otherwise */
01378           this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
01379           this->eng_list.ForceRebuild();
01380         }
01381         break;
01382     }
01383     this->SetDirty();
01384   }
01385 
01386   virtual void OnResize()
01387   {
01388     this->vscroll->SetCapacityFromWidget(this, WID_BV_LIST);
01389     this->GetWidget<NWidgetCore>(WID_BV_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
01390   }
01391 };
01392 
01393 static const WindowDesc _build_vehicle_desc(
01394   WDP_AUTO, 240, 268,
01395   WC_BUILD_VEHICLE, WC_NONE,
01396   WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION,
01397   _nested_build_vehicle_widgets, lengthof(_nested_build_vehicle_widgets)
01398 );
01399 
01400 void ShowBuildVehicleWindow(TileIndex tile, VehicleType type)
01401 {
01402   /* We want to be able to open both Available Train as Available Ships,
01403    *  so if tile == INVALID_TILE (Available XXX Window), use 'type' as unique number.
01404    *  As it always is a low value, it won't collide with any real tile
01405    *  number. */
01406   uint num = (tile == INVALID_TILE) ? (int)type : tile;
01407 
01408   assert(IsCompanyBuildableVehicleType(type));
01409 
01410   DeleteWindowById(WC_BUILD_VEHICLE, num);
01411 
01412   new BuildVehicleWindow(&_build_vehicle_desc, tile, type);
01413 }