# newgrf_engine.cpp

Go to the documentation of this file.

    00001 /* $Id: newgrf_engine.cpp 17976 2009-11-05 19:46:17Z frosch $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "debug.h"
    00014 #include "train.h"
    00015 #include "roadveh.h"
    00016 #include "company_func.h"
    00017 #include "newgrf.h"
    00018 #include "newgrf_cargo.h"
    00019 #include "newgrf_engine.h"
    00020 #include "newgrf_spritegroup.h"
    00021 #include "date_func.h"
    00022 #include "vehicle_func.h"
    00023 #include "core/random_func.hpp"
    00024 #include "aircraft.h"
    00025 #include "core/smallmap_type.hpp"
    00026 #include "station_base.h"
    00027
    00028 struct WagonOverride {
    00029   EngineID *train_id;
    00030   uint trains;
    00031   CargoID cargo;
    00032   const SpriteGroup *group;
    00033 };
    00034
    00035 void SetWagonOverrideSprites(EngineID engine, CargoID cargo, const SpriteGroup *group, EngineID *train_id, uint trains)
    00036 {
    00037   Engine *e = Engine::Get(engine);
    00038   WagonOverride *wo;
    00039
    00040   assert(cargo < NUM_CARGO + 2); // Include CT_DEFAULT and CT_PURCHASE pseudo cargos.
    00041
    00042   e->overrides_count++;
    00043   e->overrides = ReallocT(e->overrides, e->overrides_count);
    00044
    00045   wo = &e->overrides[e->overrides_count - 1];
    00046   wo->group = group;
    00047   wo->cargo = cargo;
    00048   wo->trains = trains;
    00049   wo->train_id = MallocT<EngineID>(trains);
    00050   memcpy(wo->train_id, train_id, trains * sizeof *train_id);
    00051 }
    00052
    00053 const SpriteGroup *GetWagonOverrideSpriteSet(EngineID engine, CargoID cargo, EngineID overriding_engine)
    00054 {
    00055   const Engine *e = Engine::Get(engine);
    00056
    00057   /* XXX: This could turn out to be a timesink on profiles. We could
    00058    * always just dedicate 65535 bytes for an [engine][train] trampoline
    00059    * for O(1). Or O(logMlogN) and searching binary tree or smt. like
    00060    * that. --pasky */
    00061
    00062   for (uint i = 0; i < e->overrides_count; i++) {
    00063     const WagonOverride *wo = &e->overrides[i];
    00064
    00065     if (wo->cargo != cargo && wo->cargo != CT_DEFAULT) continue;
    00066
    00067     for (uint j = 0; j < wo->trains; j++) {
    00068       if (wo->train_id[j] == overriding_engine) return wo->group;
    00069     }
    00070   }
    00071   return NULL;
    00072 }
    00073
    00077 void UnloadWagonOverrides(Engine *e)
    00078 {
    00079   for (uint i = 0; i < e->overrides_count; i++) {
    00080     WagonOverride *wo = &e->overrides[i];
    00081     free(wo->train_id);
    00082   }
    00083   free(e->overrides);
    00084   e->overrides_count = 0;
    00085   e->overrides = NULL;
    00086 }
    00087
    00088
    00089 void SetCustomEngineSprites(EngineID engine, byte cargo, const SpriteGroup *group)
    00090 {
    00091   Engine *e = Engine::Get(engine);
    00092   assert(cargo < lengthof(e->group));
    00093
    00094   if (e->group[cargo] != NULL) {
    00095     grfmsg(6, "SetCustomEngineSprites: engine %d cargo %d already has group -- replacing", engine, cargo);
    00096   }
    00097   e->group[cargo] = group;
    00098 }
    00099
    00100
    00107 void SetEngineGRF(EngineID engine, const GRFFile *file)
    00108 {
    00109   Engine *e = Engine::Get(engine);
    00110   e->grffile = file;
    00111 }
    00112
    00113
    00119 const GRFFile *GetEngineGRF(EngineID engine)
    00120 {
    00121   return Engine::Get(engine)->grffile;
    00122 }
    00123
    00124
    00130 uint32 GetEngineGRFID(EngineID engine)
    00131 {
    00132   const GRFFile *file = GetEngineGRF(engine);
    00133   return file == NULL ? 0 : file->grfid;
    00134 }
    00135
    00136
    00137 static int MapOldSubType(const Vehicle *v)
    00138 {
    00139   switch (v->type) {
    00140     case VEH_TRAIN:
    00141       if (Train::From(v)->IsEngine()) return 0;
    00142       if (Train::From(v)->IsFreeWagon()) return 4;
    00143       return 2;
    00144     case VEH_ROAD:
    00145     case VEH_SHIP:     return 0;
    00146     case VEH_AIRCRAFT:
    00147     case VEH_DISASTER: return v->subtype;
    00148     case VEH_EFFECT:   return v->subtype << 1;
    00149     default: NOT_REACHED();
    00150   }
    00151 }
    00152
    00153
    00154 /* TTDP style aircraft movement states for GRF Action 2 Var 0xE2 */
    00155 enum {
    00156   AMS_TTDP_HANGAR,
    00157   AMS_TTDP_TO_HANGAR,
    00158   AMS_TTDP_TO_PAD1,
    00159   AMS_TTDP_TO_PAD2,
    00160   AMS_TTDP_TO_PAD3,
    00161   AMS_TTDP_TO_ENTRY_2_AND_3,
    00162   AMS_TTDP_TO_ENTRY_2_AND_3_AND_H,
    00163   AMS_TTDP_TO_JUNCTION,
    00164   AMS_TTDP_LEAVE_RUNWAY,
    00165   AMS_TTDP_TO_INWAY,
    00166   AMS_TTDP_TO_RUNWAY,
    00167   AMS_TTDP_TO_OUTWAY,
    00168   AMS_TTDP_WAITING,
    00169   AMS_TTDP_TAKEOFF,
    00170   AMS_TTDP_TO_TAKEOFF,
    00171   AMS_TTDP_CLIMBING,
    00172   AMS_TTDP_FLIGHT_APPROACH,
    00173   AMS_TTDP_UNUSED_0x11,
    00174   AMS_TTDP_FLIGHT_TO_TOWER,
    00175   AMS_TTDP_UNUSED_0x13,
    00176   AMS_TTDP_FLIGHT_FINAL,
    00177   AMS_TTDP_FLIGHT_DESCENT,
    00178   AMS_TTDP_BRAKING,
    00179   AMS_TTDP_HELI_TAKEOFF_AIRPORT,
    00180   AMS_TTDP_HELI_TO_TAKEOFF_AIRPORT,
    00181   AMS_TTDP_HELI_LAND_AIRPORT,
    00182   AMS_TTDP_HELI_TAKEOFF_HELIPORT,
    00183   AMS_TTDP_HELI_TO_TAKEOFF_HELIPORT,
    00184   AMS_TTDP_HELI_LAND_HELIPORT,
    00185 };
    00186
    00187
    00192 static byte MapAircraftMovementState(const Aircraft *v)
    00193 {
    00194   const Station *st = GetTargetAirportIfValid(v);
    00195   if (st == NULL) return AMS_TTDP_FLIGHT_TO_TOWER;
    00196
    00197   const AirportFTAClass *afc = st->Airport();
    00198   uint16 amdflag = afc->MovingData(v->pos)->flag;
    00199
    00200   switch (v->state) {
    00201     case HANGAR:
    00202       /* The international airport is a special case as helicopters can land in
    00203        * front of the hanger. Helicopters also change their air.state to
    00204        * AMED_HELI_LOWER some time before actually descending. */
    00205
    00206       /* This condition only occurs for helicopters, during descent,
    00207        * to a landing by the hanger of an international airport. */
    00208       if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT;
    00209
    00210       /* This condition only occurs for helicopters, before starting descent,
    00211        * to a landing by the hanger of an international airport. */
    00212       if (amdflag & AMED_SLOWTURN) return AMS_TTDP_FLIGHT_TO_TOWER;
    00213
    00214       /* The final two conditions apply to helicopters or aircraft.
    00215        * Has reached hanger? */
    00216       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_HANGAR;
    00217
    00218       /* Still moving towards hanger. */
    00219       return AMS_TTDP_TO_HANGAR;
    00220
    00221     case TERM1:
    00222       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD1;
    00223       return AMS_TTDP_TO_JUNCTION;
    00224
    00225     case TERM2:
    00226       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD2;
    00227       return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
    00228
    00229     case TERM3:
    00230     case TERM4:
    00231     case TERM5:
    00232     case TERM6:
    00233     case TERM7:
    00234     case TERM8:
    00235       /* TTDPatch only has 3 terminals, so treat these states the same */
    00236       if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD3;
    00237       return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
    00238
    00239     case HELIPAD1:
    00240     case HELIPAD2:
    00241     case HELIPAD3:
    00242     case HELIPAD4: // Will only occur for helicopters.
    00243       if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT; // Descending.
    00244       if (amdflag & AMED_SLOWTURN)   return AMS_TTDP_FLIGHT_TO_TOWER;   // Still hasn't started descent.
    00245       return AMS_TTDP_TO_JUNCTION; // On the ground.
    00246
    00247     case TAKEOFF: // Moving to takeoff position.
    00248       return AMS_TTDP_TO_OUTWAY;
    00249
    00250     case STARTTAKEOFF: // Accelerating down runway.
    00251       return AMS_TTDP_TAKEOFF;
    00252
    00253     case ENDTAKEOFF: // Ascent
    00254       return AMS_TTDP_CLIMBING;
    00255
    00256     case HELITAKEOFF: // Helicopter is moving to take off position.
    00257       if (afc->delta_z == 0) {
    00258         return amdflag & AMED_HELI_RAISE ?
    00259           AMS_TTDP_HELI_TAKEOFF_AIRPORT : AMS_TTDP_TO_JUNCTION;
    00260       } else {
    00261         return AMS_TTDP_HELI_TAKEOFF_HELIPORT;
    00262       }
    00263
    00264     case FLYING:
    00265       return amdflag & AMED_HOLD ? AMS_TTDP_FLIGHT_APPROACH : AMS_TTDP_FLIGHT_TO_TOWER;
    00266
    00267     case LANDING: // Descent
    00268       return AMS_TTDP_FLIGHT_DESCENT;
    00269
    00270     case ENDLANDING: // On the runway braking
    00271       if (amdflag & AMED_BRAKE) return AMS_TTDP_BRAKING;
    00272       /* Landed - moving off runway */
    00273       return AMS_TTDP_TO_INWAY;
    00274
    00275     case HELILANDING:
    00276     case HELIENDLANDING: // Helicoptor is decending.
    00277       if (amdflag & AMED_HELI_LOWER) {
    00278         return afc->delta_z == 0 ?
    00279           AMS_TTDP_HELI_LAND_AIRPORT : AMS_TTDP_HELI_LAND_HELIPORT;
    00280       } else {
    00281         return AMS_TTDP_FLIGHT_TO_TOWER;
    00282       }
    00283
    00284     default:
    00285       return AMS_TTDP_HANGAR;
    00286   }
    00287 }
    00288
    00289
    00290 /* TTDP style aircraft movement action for GRF Action 2 Var 0xE6 */
    00291 enum {
    00292   AMA_TTDP_IN_HANGAR,
    00293   AMA_TTDP_ON_PAD1,
    00294   AMA_TTDP_ON_PAD2,
    00295   AMA_TTDP_ON_PAD3,
    00296   AMA_TTDP_HANGAR_TO_PAD1,
    00297   AMA_TTDP_HANGAR_TO_PAD2,
    00298   AMA_TTDP_HANGAR_TO_PAD3,
    00299   AMA_TTDP_LANDING_TO_PAD1,
    00300   AMA_TTDP_LANDING_TO_PAD2,
    00301   AMA_TTDP_LANDING_TO_PAD3,
    00302   AMA_TTDP_PAD1_TO_HANGAR,
    00303   AMA_TTDP_PAD2_TO_HANGAR,
    00304   AMA_TTDP_PAD3_TO_HANGAR,
    00305   AMA_TTDP_PAD1_TO_TAKEOFF,
    00306   AMA_TTDP_PAD2_TO_TAKEOFF,
    00307   AMA_TTDP_PAD3_TO_TAKEOFF,
    00308   AMA_TTDP_HANGAR_TO_TAKOFF,
    00309   AMA_TTDP_LANDING_TO_HANGAR,
    00310   AMA_TTDP_IN_FLIGHT,
    00311 };
    00312
    00313
    00319 static byte MapAircraftMovementAction(const Aircraft *v)
    00320 {
    00321   switch (v->state) {
    00322     case HANGAR:
    00323       return (v->cur_speed > 0) ? AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_IN_HANGAR;
    00324
    00325     case TERM1:
    00326     case HELIPAD1:
    00327       return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD1 : AMA_TTDP_LANDING_TO_PAD1;
    00328
    00329     case TERM2:
    00330     case HELIPAD2:
    00331       return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD2 : AMA_TTDP_LANDING_TO_PAD2;
    00332
    00333     case TERM3:
    00334     case TERM4:
    00335     case TERM5:
    00336     case TERM6:
    00337     case TERM7:
    00338     case TERM8:
    00339     case HELIPAD3:
    00340     case HELIPAD4:
    00341       return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD3 : AMA_TTDP_LANDING_TO_PAD3;
    00342
    00343     case TAKEOFF:      // Moving to takeoff position
    00344     case STARTTAKEOFF: // Accelerating down runway
    00345     case ENDTAKEOFF:   // Ascent
    00346     case HELITAKEOFF:
    00347       /* @todo Need to find which terminal (or hanger) we've come from. How? */
    00348       return AMA_TTDP_PAD1_TO_TAKEOFF;
    00349
    00350     case FLYING:
    00351       return AMA_TTDP_IN_FLIGHT;
    00352
    00353     case LANDING:    // Descent
    00354     case ENDLANDING: // On the runway braking
    00355     case HELILANDING:
    00356     case HELIENDLANDING:
    00357       /* @todo Need to check terminal we're landing to. Is it known yet? */
    00358       return (v->current_order.IsType(OT_GOTO_DEPOT)) ?
    00359         AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_LANDING_TO_PAD1;
    00360
    00361     default:
    00362       return AMA_TTDP_IN_HANGAR;
    00363   }
    00364 }
    00365
    00366
    00367 /* TTDP airport types. Used to map our types to TTDPatch's */
    00368 enum {
    00369   ATP_TTDP_SMALL,
    00370   ATP_TTDP_LARGE,
    00371   ATP_TTDP_HELIPORT,
    00372   ATP_TTDP_OILRIG,
    00373 };
    00374
    00375
    00376 /* Vehicle Resolver Functions */
    00377 static inline const Vehicle *GRV(const ResolverObject *object)
    00378 {
    00379   switch (object->scope) {
    00380     default: NOT_REACHED();
    00381     case VSG_SCOPE_SELF: return object->u.vehicle.self;
    00382     case VSG_SCOPE_PARENT: return object->u.vehicle.parent;
    00383     case VSG_SCOPE_RELATIVE: {
    00384       const Vehicle *v = NULL;
    00385       switch (GB(object->count, 6, 2)) {
    00386         default: NOT_REACHED();
    00387         case 0x00: // count back (away from the engine), starting at this vehicle
    00388         case 0x01: // count forward (toward the engine), starting at this vehicle
    00389           v = object->u.vehicle.self;
    00390           break;
    00391         case 0x02: // count back, starting at the engine
    00392           v = object->u.vehicle.parent;
    00393           break;
    00394         case 0x03: { // count back, starting at the first vehicle in this chain of vehicles with the same ID, as for vehicle variable 41
    00395           const Vehicle *self = object->u.vehicle.self;
    00396           for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
    00397             if (u->engine_type != self->engine_type) {
    00398               v = NULL;
    00399             } else {
    00400               if (v == NULL) v = u;
    00401             }
    00402           }
    00403           if (v == NULL) v = self;
    00404         } break;
    00405       }
    00406       uint32 count = GB(object->count, 0, 4);
    00407       if (count == 0) count = GetRegister(0x100);
    00408       while (v != NULL && count-- != 0) v = (GB(object->count, 6, 2) == 0x01) ? v->Previous() : v->Next();
    00409       return v;
    00410     }
    00411   }
    00412 }
    00413
    00414
    00415 static uint32 VehicleGetRandomBits(const ResolverObject *object)
    00416 {
    00417   return GRV(object) == NULL ? 0 : GRV(object)->random_bits;
    00418 }
    00419
    00420
    00421 static uint32 VehicleGetTriggers(const ResolverObject *object)
    00422 {
    00423   return GRV(object) == NULL ? 0 : GRV(object)->waiting_triggers;
    00424 }
    00425
    00426
    00427 static void VehicleSetTriggers(const ResolverObject *object, int triggers)
    00428 {
    00429   /* Evil cast to get around const-ness. This used to be achieved by an
    00430    * innocent looking function pointer cast... Currently I cannot see a
    00431    * way of avoiding this without removing consts deep within gui code.
    00432    */
    00433   Vehicle *v = const_cast<Vehicle *>(GRV(object));
    00434
    00435   /* This function must only be called when processing triggers -- any
    00436    * other time is an error. */
    00437   assert(object->trigger != 0);
    00438
    00439   if (v != NULL) v->waiting_triggers = triggers;
    00440 }
    00441
    00442
    00443 static uint8 LiveryHelper(EngineID engine, const Vehicle *v)
    00444 {
    00445   const Livery *l;
    00446
    00447   if (v == NULL) {
    00448     if (!Company::IsValidID(_current_company)) return 0;
    00449     l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL);
    00450   } else if (v->type == VEH_TRAIN) {
    00451     l = GetEngineLivery(v->engine_type, v->owner, Train::From(v)->tcache.first_engine, v);
    00452   } else if (v->type == VEH_ROAD) {
    00453     l = GetEngineLivery(v->engine_type, v->owner, RoadVehicle::From(v)->rcache.first_engine, v);
    00454   } else {
    00455     l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v);
    00456   }
    00457
    00458   return l->colour1 + l->colour2 * 16;
    00459 }
    00460
    00468 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
    00469 {
    00470   const Vehicle *u;
    00471   byte chain_before = 0;
    00472   byte chain_after  = 0;
    00473
    00474   for (u = v->First(); u != v; u = u->Next()) {
    00475     chain_before++;
    00476     if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
    00477   }
    00478
    00479   while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
    00480     chain_after++;
    00481     u = u->Next();
    00482   }
    00483
    00484   return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
    00485 }
    00486
    00487 static uint32 VehicleGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
    00488 {
    00489   Vehicle *v = const_cast<Vehicle*>(GRV(object));
    00490
    00491   if (v == NULL) {
    00492     /* Vehicle does not exist, so we're in a purchase list */
    00493     switch (variable) {
    00494       case 0x43: return _current_company | (LiveryHelper(object->u.vehicle.self_type, NULL) << 24); // Owner information
    00495       case 0x46: return 0;               // Motion counter
    00496       case 0x47: { // Vehicle cargo info
    00497         const Engine *e = Engine::Get(object->u.vehicle.self_type);
    00498         CargoID cargo_type = e->GetDefaultCargoType();
    00499         if (cargo_type != CT_INVALID) {
    00500           const CargoSpec *cs = CargoSpec::Get(cargo_type);
    00501           return (cs->classes << 16) | (cs->weight << 8) | GetEngineGRF(e->index)->cargo_map[cargo_type];
    00502         } else {
    00503           return 0x000000FF;
    00504         }
    00505       }
    00506       case 0x48: return Engine::Get(object->u.vehicle.self_type)->flags; // Vehicle Type Info
    00507       case 0x49: return _cur_year; // 'Long' format build year
    00508       case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
    00509       case 0xDA: return INVALID_VEHICLE; // Next vehicle
    00510       case 0xF2: return 0; // Cargo subtype
    00511     }
    00512
    00513     *available = false;
    00514     return UINT_MAX;
    00515   }
    00516
    00517   /* Calculated vehicle parameters */
    00518   switch (variable) {
    00519     case 0x25: // Get engine GRF ID
    00520       return GetEngineGRFID(v->engine_type);
    00521
    00522     case 0x40: // Get length of consist
    00523       if (!HasBit(v->vcache.cache_valid, 0)) {
    00524         v->vcache.cached_var40 = PositionHelper(v, false);
    00525         SetBit(v->vcache.cache_valid, 0);
    00526       }
    00527       return v->vcache.cached_var40;
    00528
    00529     case 0x41: // Get length of same consecutive wagons
    00530       if (!HasBit(v->vcache.cache_valid, 1)) {
    00531         v->vcache.cached_var41 = PositionHelper(v, true);
    00532         SetBit(v->vcache.cache_valid, 1);
    00533       }
    00534       return v->vcache.cached_var41;
    00535
    00536     case 0x42: // Consist cargo information
    00537       if (!HasBit(v->vcache.cache_valid, 2)) {
    00538         const Vehicle *u;
    00539         byte cargo_classes = 0;
    00540         uint8 common_cargos[NUM_CARGO];
    00541         uint8 common_subtypes[256];
    00542         byte user_def_data = 0;
    00543         CargoID common_cargo_type = CT_INVALID;
    00544         uint8 common_subtype = 0xFF; // Return 0xFF if nothing is carried
    00545
    00546         /* Reset our arrays */
    00547         memset(common_cargos, 0, sizeof(common_cargos));
    00548         memset(common_subtypes, 0, sizeof(common_subtypes));
    00549
    00550         for (u = v; u != NULL; u = u->Next()) {
    00551           if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
    00552
    00553           /* Skip empty engines */
    00554           if (u->cargo_cap == 0) continue;
    00555
    00556           cargo_classes |= CargoSpec::Get(u->cargo_type)->classes;
    00557           common_cargos[u->cargo_type]++;
    00558         }
    00559
    00560         /* Pick the most common cargo type */
    00561         uint common_cargo_best_amount = 0;
    00562         for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
    00563           if (common_cargos[cargo] > common_cargo_best_amount) {
    00564             common_cargo_best_amount = common_cargos[cargo];
    00565             common_cargo_type = cargo;
    00566           }
    00567         }
    00568
    00569         /* Count subcargo types of common_cargo_type */
    00570         for (u = v; u != NULL; u = u->Next()) {
    00571           /* Skip empty engines and engines not carrying common_cargo_type */
    00572           if (u->cargo_cap == 0 || u->cargo_type != common_cargo_type) continue;
    00573
    00574           common_subtypes[u->cargo_subtype]++;
    00575         }
    00576
    00577         /* Pick the most common subcargo type*/
    00578         uint common_subtype_best_amount = 0;
    00579         for (uint i = 0; i < lengthof(common_subtypes); i++) {
    00580           if (common_subtypes[i] > common_subtype_best_amount) {
    00581             common_subtype_best_amount = common_subtypes[i];
    00582             common_subtype = i;
    00583           }
    00584         }
    00585
    00586         uint8 common_bitnum = (common_cargo_type == CT_INVALID ? 0xFF : CargoSpec::Get(common_cargo_type)->bitnum);
    00587         v->vcache.cached_var42 = cargo_classes | (common_bitnum << 8) | (common_subtype << 16) | (user_def_data << 24);
    00588         SetBit(v->vcache.cache_valid, 2);
    00589       }
    00590       return v->vcache.cached_var42;
    00591
    00592     case 0x43: // Company information
    00593       if (!HasBit(v->vcache.cache_valid, 3)) {
    00594         v->vcache.cached_var43 = v->owner | (Company::IsHumanID(v->owner) ? 0 : 0x10000) | (LiveryHelper(v->engine_type, v) << 24);
    00595         SetBit(v->vcache.cache_valid, 3);
    00596       }
    00597       return v->vcache.cached_var43;
    00598
    00599     case 0x44: // Aircraft information
    00600       if (v->type != VEH_AIRCRAFT) return UINT_MAX;
    00601
    00602       {
    00603         const Vehicle *w = v->Next();
    00604         uint16 altitude = v->z_pos - w->z_pos; // Aircraft height - shadow height
    00605         byte airporttype = ATP_TTDP_LARGE;
    00606
    00607         const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
    00608
    00609         if (st != NULL) {
    00610           switch (st->airport_type) {
    00611             /* Note, Helidepot and Helistation are treated as small airports
    00612              * as they are at ground level. */
    00613             case AT_HELIDEPOT:
    00614             case AT_HELISTATION:
    00615             case AT_COMMUTER:
    00616             case AT_SMALL:         airporttype = ATP_TTDP_SMALL; break;
    00617             case AT_METROPOLITAN:
    00618             case AT_INTERNATIONAL:
    00619             case AT_INTERCON:
    00620             case AT_LARGE:         airporttype = ATP_TTDP_LARGE; break;
    00621             case AT_HELIPORT:      airporttype = ATP_TTDP_HELIPORT; break;
    00622             case AT_OILRIG:        airporttype = ATP_TTDP_OILRIG; break;
    00623             default:               airporttype = ATP_TTDP_LARGE; break;
    00624           }
    00625         }
    00626
    00627         return (altitude << 8) | airporttype;
    00628       }
    00629
    00630     case 0x45: { // Curvature info
    00631       /* Format: xxxTxBxF
    00632        * F - previous wagon to current wagon, 0 if vehicle is first
    00633        * B - current wagon to next wagon, 0 if wagon is last
    00634        * T - previous wagon to next wagon, 0 in an S-bend
    00635        */
    00636       if (v->type != VEH_TRAIN && v->type != VEH_ROAD) return 0;
    00637
    00638       const Vehicle *u_p = v->Previous();
    00639       const Vehicle *u_n = v->Next();
    00640       DirDiff f = (u_p == NULL) ?  DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
    00641       DirDiff b = (u_n == NULL) ?  DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
    00642       DirDiff t = ChangeDirDiff(f, b);
    00643
    00644       return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
    00645              ((b > DIRDIFF_REVERSE ? b | 8 : b) <<  8) |
    00646              ( f > DIRDIFF_REVERSE ? f | 8 : f);
    00647     }
    00648
    00649     case 0x46: // Motion counter
    00650       return v->motion_counter;
    00651
    00652     case 0x47: { // Vehicle cargo info
    00653       /* Format: ccccwwtt
    00654        * tt - the cargo type transported by the vehicle,
    00655        *     translated if a translation table has been installed.
    00656        * ww - cargo unit weight in 1/16 tons, same as cargo prop. 0F.
    00657        * cccc - the cargo class value of the cargo transported by the vehicle.
    00658        */
    00659       const CargoSpec *cs = CargoSpec::Get(v->cargo_type);
    00660
    00661       return (cs->classes << 16) | (cs->weight << 8) | GetEngineGRF(v->engine_type)->cargo_map[v->cargo_type];
    00662     }
    00663
    00664     case 0x48: return Engine::Get(v->engine_type)->flags; // Vehicle Type Info
    00665     case 0x49: return v->build_year;
    00666
    00667     /* Variables which use the parameter */
    00668     case 0x60: // Count consist's engine ID occurance
    00669       //EngineID engine = GetNewEngineID(GetEngineGRF(v->engine_type), v->type, parameter);
    00670       if (v->type != VEH_TRAIN) return Engine::Get(v->engine_type)->internal_id == parameter;
    00671
    00672       {
    00673         uint count = 0;
    00674         for (; v != NULL; v = v->Next()) {
    00675           if (Engine::Get(v->engine_type)->internal_id == parameter) count++;
    00676         }
    00677         return count;
    00678       }
    00679
    00680     case 0xFE:
    00681     case 0xFF: {
    00682       uint16 modflags = 0;
    00683
    00684       if (v->type == VEH_TRAIN) {
    00685         const Train *t = Train::From(v);
    00686         const Train *u = t->IsWagon() && HasBit(t->vehicle_flags, VRF_POWEREDWAGON) ? t->First() : t;
    00687         RailType railtype = GetRailType(v->tile);
    00688         bool powered = t->IsEngine() || (t->IsWagon() && HasBit(t->vehicle_flags, VRF_POWEREDWAGON));
    00689         bool has_power = powered && HasPowerOnRail(u->railtype, railtype);
    00690         bool is_electric = powered && u->railtype == RAILTYPE_ELECTRIC;
    00691
    00692         if (has_power) SetBit(modflags, 5);
    00693         if (is_electric && !has_power) SetBit(modflags, 6);
    00694         if (HasBit(t->flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
    00695       }
    00696       if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
    00697
    00698       return variable == 0xFE ? modflags : GB(modflags, 8, 8);
    00699     }
    00700   }
    00701
    00702   /* General vehicle properties */
    00703   switch (variable - 0x80) {
    00704     case 0x00: return v->type + 0x10;
    00705     case 0x01: return MapOldSubType(v);
    00706     case 0x04: return v->index;
    00707     case 0x05: return GB(v->index, 8, 8);
    00708     case 0x0A: return v->current_order.MapOldOrder();
    00709     case 0x0B: return v->current_order.GetDestination();
    00710     case 0x0C: return v->GetNumOrders();
    00711     case 0x0D: return v->cur_order_index;
    00712     case 0x10: return v->time_counter;
    00713     case 0x11: return GB(v->time_counter, 8, 8);
    00714     case 0x12: return max(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
    00715     case 0x13: return GB(max(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0), 8, 8);
    00716     case 0x14: return v->service_interval;
    00717     case 0x15: return GB(v->service_interval, 8, 8);
    00718     case 0x16: return v->last_station_visited;
    00719     case 0x17: return v->tick_counter;
    00720     case 0x18: return v->max_speed;
    00721     case 0x19: return GB(v->max_speed, 8, 8);
    00722     case 0x1A: return v->x_pos;
    00723     case 0x1B: return GB(v->x_pos, 8, 8);
    00724     case 0x1C: return v->y_pos;
    00725     case 0x1D: return GB(v->y_pos, 8, 8);
    00726     case 0x1E: return v->z_pos;
    00727     case 0x1F: return object->u.vehicle.info_view ? DIR_W : v->direction;
    00728     case 0x28: return v->cur_image;
    00729     case 0x29: return GB(v->cur_image, 8, 8);
    00730     case 0x32: return v->vehstatus;
    00731     case 0x33: return 0; // non-existent high byte of vehstatus
    00732     case 0x34: return v->cur_speed;
    00733     case 0x35: return GB(v->cur_speed, 8, 8);
    00734     case 0x36: return v->subspeed;
    00735     case 0x37: return v->acceleration;
    00736     case 0x39: return v->cargo_type;
    00737     case 0x3A: return v->cargo_cap;
    00738     case 0x3B: return GB(v->cargo_cap, 8, 8);
    00739     case 0x3C: return v->cargo.Count();
    00740     case 0x3D: return GB(v->cargo.Count(), 8, 8);
    00741     case 0x3E: return v->cargo.Source();
    00742     case 0x3F: return v->cargo.DaysInTransit();
    00743     case 0x40: return v->age;
    00744     case 0x41: return GB(v->age, 8, 8);
    00745     case 0x42: return v->max_age;
    00746     case 0x43: return GB(v->max_age, 8, 8);
    00747     case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
    00748     case 0x45: return v->unitnumber;
    00749     case 0x46: return Engine::Get(v->engine_type)->internal_id;
    00750     case 0x47: return GB(Engine::Get(v->engine_type)->internal_id, 8, 8);
    00751     case 0x48:
    00752       if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
    00753       return HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
    00754
    00755     case 0x49: return v->day_counter;
    00756     case 0x4A: return v->breakdowns_since_last_service;
    00757     case 0x4B: return v->breakdown_ctr;
    00758     case 0x4C: return v->breakdown_delay;
    00759     case 0x4D: return v->breakdown_chance;
    00760     case 0x4E: return v->reliability;
    00761     case 0x4F: return GB(v->reliability, 8, 8);
    00762     case 0x50: return v->reliability_spd_dec;
    00763     case 0x51: return GB(v->reliability_spd_dec, 8, 8);
    00764     case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
    00765     case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()),  8, 24);
    00766     case 0x54: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 16, 16);
    00767     case 0x55: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 24,  8);
    00768     case 0x56: return ClampToI32(v->GetDisplayProfitLastYear());
    00769     case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()),  8, 24);
    00770     case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
    00771     case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24,  8);
    00772     case 0x5A: return v->Next() == NULL ? INVALID_VEHICLE : v->Next()->index;
    00773     case 0x5C: return ClampToI32(v->value);
    00774     case 0x5D: return GB(ClampToI32(v->value),  8, 24);
    00775     case 0x5E: return GB(ClampToI32(v->value), 16, 16);
    00776     case 0x5F: return GB(ClampToI32(v->value), 24,  8);
    00777     case 0x72: return v->cargo_subtype;
    00778     case 0x7A: return v->random_bits;
    00779     case 0x7B: return v->waiting_triggers;
    00780   }
    00781
    00782   /* Vehicle specific properties */
    00783   switch (v->type) {
    00784     case VEH_TRAIN: {
    00785       Train *t = Train::From(v);
    00786       switch (variable - 0x80) {
    00787         case 0x62: return t->track;
    00788         case 0x66: return t->railtype;
    00789         case 0x73: return t->tcache.cached_veh_length;
    00790         case 0x74: return t->tcache.cached_power;
    00791         case 0x75: return GB(t->tcache.cached_power,  8, 24);
    00792         case 0x76: return GB(t->tcache.cached_power, 16, 16);
    00793         case 0x77: return GB(t->tcache.cached_power, 24,  8);
    00794         case 0x7C: return t->First()->index;
    00795         case 0x7D: return GB(t->First()->index, 8, 8);
    00796         case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
    00797       }
    00798     } break;
    00799
    00800     case VEH_ROAD: {
    00801       RoadVehicle *rv = RoadVehicle::From(v);
    00802       switch (variable - 0x80) {
    00803         case 0x62: return rv->state;
    00804         case 0x64: return rv->blocked_ctr;
    00805         case 0x65: return GB(rv->blocked_ctr, 8, 8);
    00806         case 0x66: return rv->overtaking;
    00807         case 0x67: return rv->overtaking_ctr;
    00808         case 0x68: return rv->crashed_ctr;
    00809         case 0x69: return GB(rv->crashed_ctr, 8, 8);
    00810       }
    00811     } break;
    00812
    00813     case VEH_AIRCRAFT: {
    00814       Aircraft *a = Aircraft::From(v);
    00815       switch (variable - 0x80) {
    00816         case 0x62: return MapAircraftMovementState(a);  // Current movement state
    00817         case 0x63: return a->targetairport;             // Airport to which the action refers
    00818         case 0x66: return MapAircraftMovementAction(a); // Current movement action
    00819       }
    00820     } break;
    00821
    00822     default: break;
    00823   }
    00824
    00825   DEBUG(grf, 1, "Unhandled vehicle property 0x%X, type 0x%X", variable, (uint)v->type);
    00826
    00827   *available = false;
    00828   return UINT_MAX;
    00829 }
    00830
    00831
    00832 static const SpriteGroup *VehicleResolveReal(const ResolverObject *object, const RealSpriteGroup *group)
    00833 {
    00834   const Vehicle *v = object->u.vehicle.self;
    00835
    00836   if (v == NULL) {
    00837     if (group->num_loading > 0) return group->loading[0];
    00838     if (group->num_loaded  > 0) return group->loaded[0];
    00839     return NULL;
    00840   }
    00841
    00842   bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
    00843
    00844   uint totalsets = in_motion ? group->num_loaded : group->num_loading;
    00845
    00846   uint set = (v->cargo.Count() * totalsets) / max((uint16)1, v->cargo_cap);
    00847   set = min(set, totalsets - 1);
    00848
    00849   return in_motion ? group->loaded[set] : group->loading[set];
    00850 }
    00851
    00852
    00853 static inline void NewVehicleResolver(ResolverObject *res, EngineID engine_type, const Vehicle *v)
    00854 {
    00855   res->GetRandomBits = &VehicleGetRandomBits;
    00856   res->GetTriggers   = &VehicleGetTriggers;
    00857   res->SetTriggers   = &VehicleSetTriggers;
    00858   res->GetVariable   = &VehicleGetVariable;
    00859   res->ResolveReal   = &VehicleResolveReal;
    00860
    00861   res->u.vehicle.self   = v;
    00862   res->u.vehicle.parent = (v != NULL) ? v->First() : v;
    00863
    00864   res->u.vehicle.self_type = engine_type;
    00865   res->u.vehicle.info_view = false;
    00866
    00867   res->callback        = CBID_NO_CALLBACK;
    00868   res->callback_param1 = 0;
    00869   res->callback_param2 = 0;
    00870   res->last_value      = 0;
    00871   res->trigger         = 0;
    00872   res->reseed          = 0;
    00873   res->count           = 0;
    00874
    00875   const Engine *e = Engine::Get(engine_type);
    00876   res->grffile         = (e != NULL ? e->grffile : NULL);
    00877 }
    00878
    00879
    00888 static const SpriteGroup *GetVehicleSpriteGroup(EngineID engine, const Vehicle *v, bool use_cache = true)
    00889 {
    00890   const SpriteGroup *group;
    00891   CargoID cargo;
    00892
    00893   if (v == NULL) {
    00894     cargo = CT_PURCHASE;
    00895   } else {
    00896     cargo = v->cargo_type;
    00897
    00898     if (v->type == VEH_TRAIN) {
    00899       /* We always use cached value, except for callbacks because the override spriteset
    00900        * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
    00901        * as v->cargo_type is temporary changed to the new type */
    00902       group = use_cache ? Train::From(v)->tcache.cached_override : GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, Train::From(v)->tcache.first_engine);
    00903       if (group != NULL) return group;
    00904     } else if (v->type == VEH_ROAD) {
    00905       group = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, RoadVehicle::From(v)->rcache.first_engine);
    00906       if (group != NULL) return group;
    00907     }
    00908   }
    00909
    00910   const Engine *e = Engine::Get(engine);
    00911
    00912   assert(cargo < lengthof(e->group));
    00913   group = e->group[cargo];
    00914   if (group != NULL) return group;
    00915
    00916   /* Fall back to the default set if the selected cargo type is not defined */
    00917   return e->group[CT_DEFAULT];
    00918 }
    00919
    00920
    00921 SpriteID GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction)
    00922 {
    00923   const SpriteGroup *group;
    00924   ResolverObject object;
    00925
    00926   NewVehicleResolver(&object, engine, v);
    00927
    00928   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v), &object);
    00929   if (group == NULL || group->GetNumResults() == 0) return 0;
    00930
    00931   return group->GetResult() + (direction % group->GetNumResults());
    00932 }
    00933
    00934
    00935 SpriteID GetRotorOverrideSprite(EngineID engine, const Aircraft *v, bool info_view)
    00936 {
    00937   const Engine *e = Engine::Get(engine);
    00938
    00939   /* Only valid for helicopters */
    00940   assert(e->type == VEH_AIRCRAFT);
    00941   assert(!(e->u.air.subtype & AIR_CTOL));
    00942
    00943   ResolverObject object;
    00944
    00945   NewVehicleResolver(&object, engine, v);
    00946
    00947   object.u.vehicle.info_view = info_view;
    00948
    00949   const SpriteGroup *group = GetWagonOverrideSpriteSet(engine, CT_DEFAULT, engine);
    00950   group = SpriteGroup::Resolve(group, &object);
    00951
    00952   if (group == NULL || group->GetNumResults() == 0) return 0;
    00953
    00954   if (v == NULL) return group->GetResult();
    00955
    00956   return group->GetResult() + (info_view ? 0 : (v->Next()->Next()->state % group->GetNumResults()));
    00957 }
    00958
    00959
    00965 bool UsesWagonOverride(const Vehicle *v)
    00966 {
    00967   assert(v->type == VEH_TRAIN);
    00968   return Train::From(v)->tcache.cached_override != NULL;
    00969 }
    00970
    00980 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
    00981 {
    00982   const SpriteGroup *group;
    00983   ResolverObject object;
    00984
    00985   NewVehicleResolver(&object, engine, v);
    00986
    00987   object.callback        = callback;
    00988   object.callback_param1 = param1;
    00989   object.callback_param2 = param2;
    00990
    00991   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
    00992   if (group == NULL) return CALLBACK_FAILED;
    00993
    00994   return group->GetCallbackResult();
    00995 }
    00996
    01007 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
    01008 {
    01009   const SpriteGroup *group;
    01010   ResolverObject object;
    01011
    01012   NewVehicleResolver(&object, engine, v);
    01013
    01014   object.callback        = callback;
    01015   object.callback_param1 = param1;
    01016   object.callback_param2 = param2;
    01017
    01018   object.u.vehicle.parent = parent;
    01019
    01020   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
    01021   if (group == NULL) return CALLBACK_FAILED;
    01022
    01023   return group->GetCallbackResult();
    01024 }
    01025
    01026
    01027 /* Callback 36 handlers */
    01028 uint GetVehicleProperty(const Vehicle *v, PropertyID property, uint orig_value)
    01029 {
    01030   uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, v->engine_type, v);
    01031   if (callback != CALLBACK_FAILED) return callback;
    01032
    01033   return orig_value;
    01034 }
    01035
    01036
    01037 uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value)
    01038 {
    01039   uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, engine, NULL);
    01040   if (callback != CALLBACK_FAILED) return callback;
    01041
    01042   return orig_value;
    01043 }
    01044
    01045
    01046 static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
    01047 {
    01048   const SpriteGroup *group;
    01049   ResolverObject object;
    01050   byte new_random_bits;
    01051
    01052   /* We can't trigger a non-existent vehicle... */
    01053   assert(v != NULL);
    01054
    01055   NewVehicleResolver(&object, v->engine_type, v);
    01056   object.callback = CBID_RANDOM_TRIGGER;
    01057   object.trigger = trigger;
    01058
    01059   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(v->engine_type, v), &object);
    01060   if (group == NULL) return;
    01061
    01062   new_random_bits = Random();
    01063   v->random_bits &= ~object.reseed;
    01064   v->random_bits |= (first ? new_random_bits : base_random_bits) & object.reseed;
    01065
    01066   switch (trigger) {
    01067     case VEHICLE_TRIGGER_NEW_CARGO:
    01068       /* All vehicles in chain get ANY_NEW_CARGO trigger now.
    01069        * So we call it for the first one and they will recurse.
    01070        * Indexing part of vehicle random bits needs to be
    01071        * same for all triggered vehicles in the chain (to get
    01072        * all the random-cargo wagons carry the same cargo,
    01073        * i.e.), so we give them all the NEW_CARGO triggered
    01074        * vehicle's portion of random bits. */
    01075       assert(first);
    01076       DoTriggerVehicle(v->First(), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
    01077       break;
    01078
    01079     case VEHICLE_TRIGGER_DEPOT:
    01080       /* We now trigger the next vehicle in chain recursively.
    01081        * The random bits portions may be different for each
    01082        * vehicle in chain. */
    01083       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, 0, true);
    01084       break;
    01085
    01086     case VEHICLE_TRIGGER_EMPTY:
    01087       /* We now trigger the next vehicle in chain
    01088        * recursively.  The random bits portions must be same
    01089        * for each vehicle in chain, so we give them all
    01090        * first chained vehicle's portion of random bits. */
    01091       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
    01092       break;
    01093
    01094     case VEHICLE_TRIGGER_ANY_NEW_CARGO:
    01095       /* Now pass the trigger recursively to the next vehicle
    01096        * in chain. */
    01097       assert(!first);
    01098       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
    01099       break;
    01100
    01101     case VEHICLE_TRIGGER_CALLBACK_32:
    01102       /* Do not do any recursion */
    01103       break;
    01104   }
    01105 }
    01106
    01107 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
    01108 {
    01109   if (trigger == VEHICLE_TRIGGER_DEPOT) {
    01110     /* store that the vehicle entered a depot this tick */
    01111     VehicleEnteredDepotThisTick(v);
    01112   }
    01113
    01114   v->InvalidateNewGRFCacheOfChain();
    01115   DoTriggerVehicle(v, trigger, 0, true);
    01116   v->InvalidateNewGRFCacheOfChain();
    01117 }
    01118
    01119 /* Functions for changing the order of vehicle purchase lists
    01120  * This is currently only implemented for rail vehicles. */
    01121
    01128 uint ListPositionOfEngine(EngineID engine)
    01129 {
    01130   const Engine *e = Engine::Get(engine);
    01131   if (e->grffile == NULL) return e->list_position;
    01132
    01133   /* Crude sorting to group by GRF ID */
    01134   return (e->grffile->grfid * 256) + e->list_position;
    01135 }
    01136
    01137 struct ListOrderChange {
    01138   EngineID engine;
    01139   EngineID target;
    01140 };
    01141
    01142 static SmallVector<ListOrderChange, 16> _list_order_changes;
    01143
    01144 void AlterVehicleListOrder(EngineID engine, EngineID target)
    01145 {
    01146   /* Add the list order change to a queue */
    01147   ListOrderChange *loc = _list_order_changes.Append();
    01148   loc->engine = engine;
    01149   loc->target = target;
    01150 }
    01151
    01152 void CommitVehicleListOrderChanges()
    01153 {
    01154   /* List position to Engine map */
    01155   typedef SmallMap<uint16, Engine *, 16> ListPositionMap;
    01156   ListPositionMap lptr_map;
    01157
    01158   const ListOrderChange *end = _list_order_changes.End();
    01159   for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) {
    01160     EngineID engine = it->engine;
    01161     EngineID target = it->target;
    01162
    01163     if (engine == target) continue;
    01164
    01165     Engine *source_e = Engine::Get(engine);
    01166     Engine *target_e = NULL;
    01167
    01168     /* Populate map with current list positions */
    01169     Engine *e;
    01170     FOR_ALL_ENGINES_OF_TYPE(e, source_e->type) {
    01171       if (!_settings_game.vehicle.dynamic_engines || e->grffile == source_e->grffile) {
    01172         if (e->internal_id == target) target_e = e;
    01173         lptr_map[e->list_position] = e;
    01174       }
    01175     }
    01176
    01177     /* std::map sorted by default, SmallMap does not */
    01178     lptr_map.SortByKey();
    01179
    01180     /* Get the target position, if it exists */
    01181     if (target_e != NULL) {
    01182       uint16 target_position = target_e->list_position;
    01183
    01184       bool moving = false;
    01185       const ListPositionMap::Pair *end = lptr_map.End();
    01186       for (ListPositionMap::Pair *it = lptr_map.Begin(); it != end; ++it) {
    01187         if (it->first == target_position) moving = true;
    01188         if (moving) it->second->list_position++;
    01189       }
    01190
    01191       source_e->list_position = target_position;
    01192     }
    01193
    01194     lptr_map.Clear();
    01195   }
    01196
    01197   /* Clear out the queue */
    01198   _list_order_changes.Reset();
    01199 }