build_vehicle_gui.cpp

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