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