# newgrf_engine.cpp

Go to the documentation of this file.

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