build_vehicle_gui.cpp

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