# newgrf_engine.cpp

Go to the documentation of this file.

    00001 /* $Id: newgrf_engine.cpp 19857 2010-05-18 21:44:47Z 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       if (object->u.vehicle.self == NULL) return NULL;
    00387       const Vehicle *v = NULL;
    00388       switch (GB(object->count, 6, 2)) {
    00389         default: NOT_REACHED();
    00390         case 0x00: // count back (away from the engine), starting at this vehicle
    00391         case 0x01: // count forward (toward the engine), starting at this vehicle
    00392           v = object->u.vehicle.self;
    00393           break;
    00394         case 0x02: // count back, starting at the engine
    00395           v = object->u.vehicle.parent;
    00396           break;
    00397         case 0x03: { // count back, starting at the first vehicle in this chain of vehicles with the same ID, as for vehicle variable 41
    00398           const Vehicle *self = object->u.vehicle.self;
    00399           for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
    00400             if (u->engine_type != self->engine_type) {
    00401               v = NULL;
    00402             } else {
    00403               if (v == NULL) v = u;
    00404             }
    00405           }
    00406           if (v == NULL) v = self;
    00407         } break;
    00408       }
    00409       uint32 count = GB(object->count, 0, 4);
    00410       if (count == 0) count = GetRegister(0x100);
    00411       while (v != NULL && count-- != 0) v = (GB(object->count, 6, 2) == 0x01) ? v->Previous() : v->Next();
    00412       return v;
    00413     }
    00414   }
    00415 }
    00416
    00417
    00418 static uint32 VehicleGetRandomBits(const ResolverObject *object)
    00419 {
    00420   return GRV(object) == NULL ? 0 : GRV(object)->random_bits;
    00421 }
    00422
    00423
    00424 static uint32 VehicleGetTriggers(const ResolverObject *object)
    00425 {
    00426   return GRV(object) == NULL ? 0 : GRV(object)->waiting_triggers;
    00427 }
    00428
    00429
    00430 static void VehicleSetTriggers(const ResolverObject *object, int triggers)
    00431 {
    00432   /* Evil cast to get around const-ness. This used to be achieved by an
    00433    * innocent looking function pointer cast... Currently I cannot see a
    00434    * way of avoiding this without removing consts deep within gui code.
    00435    */
    00436   Vehicle *v = const_cast<Vehicle *>(GRV(object));
    00437
    00438   /* This function must only be called when processing triggers -- any
    00439    * other time is an error. */
    00440   assert(object->trigger != 0);
    00441
    00442   if (v != NULL) v->waiting_triggers = triggers;
    00443 }
    00444
    00445
    00446 static uint8 LiveryHelper(EngineID engine, const Vehicle *v)
    00447 {
    00448   const Livery *l;
    00449
    00450   if (v == NULL) {
    00451     if (!Company::IsValidID(_current_company)) return 0;
    00452     l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL);
    00453   } else if (v->type == VEH_TRAIN) {
    00454     l = GetEngineLivery(v->engine_type, v->owner, Train::From(v)->tcache.first_engine, v);
    00455   } else if (v->type == VEH_ROAD) {
    00456     l = GetEngineLivery(v->engine_type, v->owner, RoadVehicle::From(v)->rcache.first_engine, v);
    00457   } else {
    00458     l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v);
    00459   }
    00460
    00461   return l->colour1 + l->colour2 * 16;
    00462 }
    00463
    00471 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
    00472 {
    00473   const Vehicle *u;
    00474   byte chain_before = 0;
    00475   byte chain_after  = 0;
    00476
    00477   for (u = v->First(); u != v; u = u->Next()) {
    00478     chain_before++;
    00479     if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
    00480   }
    00481
    00482   while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
    00483     chain_after++;
    00484     u = u->Next();
    00485   }
    00486
    00487   return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
    00488 }
    00489
    00490 byte MapAirportTypeToTTDType(byte ottd_type)
    00491 {
    00492   switch (ottd_type) {
    00493     /* Note, Helidepot and Helistation are treated as small airports
    00494      * as they are at ground level. */
    00495     case AT_HELIDEPOT:
    00496     case AT_HELISTATION:
    00497     case AT_COMMUTER:
    00498     case AT_SMALL:         return ATP_TTDP_SMALL;
    00499     case AT_METROPOLITAN:
    00500     case AT_INTERNATIONAL:
    00501     case AT_INTERCON:
    00502     case AT_LARGE:         return ATP_TTDP_LARGE;
    00503     case AT_HELIPORT:      return ATP_TTDP_HELIPORT;
    00504     case AT_OILRIG:        return ATP_TTDP_OILRIG;
    00505     default:               return ATP_TTDP_LARGE;
    00506   }
    00507 }
    00508
    00509 static uint32 VehicleGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
    00510 {
    00511   Vehicle *v = const_cast<Vehicle*>(GRV(object));
    00512
    00513   if (v == NULL) {
    00514     /* Vehicle does not exist, so we're in a purchase list */
    00515     switch (variable) {
    00516       case 0x43: return _current_company | (Company::IsValidAiID(_current_company) ? 0x10000 : 0) | (LiveryHelper(object->u.vehicle.self_type, NULL) << 24); // Owner information
    00517       case 0x46: return 0;               // Motion counter
    00518       case 0x47: { // Vehicle cargo info
    00519         const Engine *e = Engine::Get(object->u.vehicle.self_type);
    00520         CargoID cargo_type = e->GetDefaultCargoType();
    00521         if (cargo_type != CT_INVALID) {
    00522           const CargoSpec *cs = CargoSpec::Get(cargo_type);
    00523           return (cs->classes << 16) | (cs->weight << 8) | GetEngineGRF(e->index)->cargo_map[cargo_type];
    00524         } else {
    00525           return 0x000000FF;
    00526         }
    00527       }
    00528       case 0x48: return Engine::Get(object->u.vehicle.self_type)->flags; // Vehicle Type Info
    00529       case 0x49: return _cur_year; // 'Long' format build year
    00530       case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
    00531       case 0xDA: return INVALID_VEHICLE; // Next vehicle
    00532       case 0xF2: return 0; // Cargo subtype
    00533     }
    00534
    00535     *available = false;
    00536     return UINT_MAX;
    00537   }
    00538
    00539   /* Calculated vehicle parameters */
    00540   switch (variable) {
    00541     case 0x25: // Get engine GRF ID
    00542       return GetEngineGRFID(v->engine_type);
    00543
    00544     case 0x40: // Get length of consist
    00545       if (!HasBit(v->vcache.cache_valid, 0)) {
    00546         v->vcache.cached_var40 = PositionHelper(v, false);
    00547         SetBit(v->vcache.cache_valid, 0);
    00548       }
    00549       return v->vcache.cached_var40;
    00550
    00551     case 0x41: // Get length of same consecutive wagons
    00552       if (!HasBit(v->vcache.cache_valid, 1)) {
    00553         v->vcache.cached_var41 = PositionHelper(v, true);
    00554         SetBit(v->vcache.cache_valid, 1);
    00555       }
    00556       return v->vcache.cached_var41;
    00557
    00558     case 0x42: // Consist cargo information
    00559       if (!HasBit(v->vcache.cache_valid, 2)) {
    00560         const Vehicle *u;
    00561         byte cargo_classes = 0;
    00562         uint8 common_cargos[NUM_CARGO];
    00563         uint8 common_subtypes[256];
    00564         byte user_def_data = 0;
    00565         CargoID common_cargo_type = CT_INVALID;
    00566         uint8 common_subtype = 0xFF; // Return 0xFF if nothing is carried
    00567
    00568         /* Reset our arrays */
    00569         memset(common_cargos, 0, sizeof(common_cargos));
    00570         memset(common_subtypes, 0, sizeof(common_subtypes));
    00571
    00572         for (u = v; u != NULL; u = u->Next()) {
    00573           if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
    00574
    00575           /* Skip empty engines */
    00576           if (u->cargo_cap == 0) continue;
    00577
    00578           cargo_classes |= CargoSpec::Get(u->cargo_type)->classes;
    00579           common_cargos[u->cargo_type]++;
    00580         }
    00581
    00582         /* Pick the most common cargo type */
    00583         uint common_cargo_best_amount = 0;
    00584         for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
    00585           if (common_cargos[cargo] > common_cargo_best_amount) {
    00586             common_cargo_best_amount = common_cargos[cargo];
    00587             common_cargo_type = cargo;
    00588           }
    00589         }
    00590
    00591         /* Count subcargo types of common_cargo_type */
    00592         for (u = v; u != NULL; u = u->Next()) {
    00593           /* Skip empty engines and engines not carrying common_cargo_type */
    00594           if (u->cargo_cap == 0 || u->cargo_type != common_cargo_type) continue;
    00595
    00596           common_subtypes[u->cargo_subtype]++;
    00597         }
    00598
    00599         /* Pick the most common subcargo type*/
    00600         uint common_subtype_best_amount = 0;
    00601         for (uint i = 0; i < lengthof(common_subtypes); i++) {
    00602           if (common_subtypes[i] > common_subtype_best_amount) {
    00603             common_subtype_best_amount = common_subtypes[i];
    00604             common_subtype = i;
    00605           }
    00606         }
    00607
    00608         uint8 common_bitnum = (common_cargo_type == CT_INVALID ? 0xFF : CargoSpec::Get(common_cargo_type)->bitnum);
    00609         v->vcache.cached_var42 = cargo_classes | (common_bitnum << 8) | (common_subtype << 16) | (user_def_data << 24);
    00610         SetBit(v->vcache.cache_valid, 2);
    00611       }
    00612       return v->vcache.cached_var42;
    00613
    00614     case 0x43: // Company information
    00615       if (!HasBit(v->vcache.cache_valid, 3)) {
    00616         v->vcache.cached_var43 = v->owner | (Company::IsHumanID(v->owner) ? 0 : 0x10000) | (LiveryHelper(v->engine_type, v) << 24);
    00617         SetBit(v->vcache.cache_valid, 3);
    00618       }
    00619       return v->vcache.cached_var43;
    00620
    00621     case 0x44: // Aircraft information
    00622       if (v->type != VEH_AIRCRAFT) return UINT_MAX;
    00623
    00624       {
    00625         const Vehicle *w = v->Next();
    00626         uint16 altitude = v->z_pos - w->z_pos; // Aircraft height - shadow height
    00627         byte airporttype = ATP_TTDP_LARGE;
    00628
    00629         const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
    00630
    00631         if (st != NULL) {
    00632           airporttype = MapAirportTypeToTTDType(st->airport_type);
    00633         }
    00634
    00635         return (altitude << 8) | airporttype;
    00636       }
    00637
    00638     case 0x45: { // Curvature info
    00639       /* Format: xxxTxBxF
    00640        * F - previous wagon to current wagon, 0 if vehicle is first
    00641        * B - current wagon to next wagon, 0 if wagon is last
    00642        * T - previous wagon to next wagon, 0 in an S-bend
    00643        */
    00644       if (v->type != VEH_TRAIN && v->type != VEH_ROAD) return 0;
    00645
    00646       const Vehicle *u_p = v->Previous();
    00647       const Vehicle *u_n = v->Next();
    00648       DirDiff f = (u_p == NULL) ?  DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
    00649       DirDiff b = (u_n == NULL) ?  DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
    00650       DirDiff t = ChangeDirDiff(f, b);
    00651
    00652       return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
    00653              ((b > DIRDIFF_REVERSE ? b | 8 : b) <<  8) |
    00654              ( f > DIRDIFF_REVERSE ? f | 8 : f);
    00655     }
    00656
    00657     case 0x46: // Motion counter
    00658       return v->motion_counter;
    00659
    00660     case 0x47: { // Vehicle cargo info
    00661       /* Format: ccccwwtt
    00662        * tt - the cargo type transported by the vehicle,
    00663        *     translated if a translation table has been installed.
    00664        * ww - cargo unit weight in 1/16 tons, same as cargo prop. 0F.
    00665        * cccc - the cargo class value of the cargo transported by the vehicle.
    00666        */
    00667       const CargoSpec *cs = CargoSpec::Get(v->cargo_type);
    00668
    00669       return (cs->classes << 16) | (cs->weight << 8) | GetEngineGRF(v->engine_type)->cargo_map[v->cargo_type];
    00670     }
    00671
    00672     case 0x48: return Engine::Get(v->engine_type)->flags; // Vehicle Type Info
    00673     case 0x49: return v->build_year;
    00674
    00675     /* Variables which use the parameter */
    00676     case 0x60: // Count consist's engine ID occurance
    00677       //EngineID engine = GetNewEngineID(GetEngineGRF(v->engine_type), v->type, parameter);
    00678       if (v->type != VEH_TRAIN) return Engine::Get(v->engine_type)->internal_id == parameter;
    00679
    00680       {
    00681         uint count = 0;
    00682         for (; v != NULL; v = v->Next()) {
    00683           if (Engine::Get(v->engine_type)->internal_id == parameter) count++;
    00684         }
    00685         return count;
    00686       }
    00687
    00688     case 0xFE:
    00689     case 0xFF: {
    00690       uint16 modflags = 0;
    00691
    00692       if (v->type == VEH_TRAIN) {
    00693         const Train *t = Train::From(v);
    00694         const Train *u = t->IsWagon() && HasBit(t->vehicle_flags, VRF_POWEREDWAGON) ? t->First() : t;
    00695         RailType railtype = GetRailType(v->tile);
    00696         bool powered = t->IsEngine() || (t->IsWagon() && HasBit(t->vehicle_flags, VRF_POWEREDWAGON));
    00697         bool has_power = powered && HasPowerOnRail(u->railtype, railtype);
    00698         bool is_electric = powered && u->railtype == RAILTYPE_ELECTRIC;
    00699
    00700         if (has_power) SetBit(modflags, 5);
    00701         if (is_electric && !has_power) SetBit(modflags, 6);
    00702         if (HasBit(t->flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
    00703       }
    00704       if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
    00705
    00706       return variable == 0xFE ? modflags : GB(modflags, 8, 8);
    00707     }
    00708   }
    00709
    00710   /* General vehicle properties */
    00711   switch (variable - 0x80) {
    00712     case 0x00: return v->type + 0x10;
    00713     case 0x01: return MapOldSubType(v);
    00714     case 0x04: return v->index;
    00715     case 0x05: return GB(v->index, 8, 8);
    00716     case 0x0A: return v->current_order.MapOldOrder();
    00717     case 0x0B: return v->current_order.GetDestination();
    00718     case 0x0C: return v->GetNumOrders();
    00719     case 0x0D: return v->cur_order_index;
    00720     case 0x10:
    00721     case 0x11: {
    00722       uint ticks;
    00723       if (v->current_order.IsType(OT_LOADING)) {
    00724         ticks = v->load_unload_ticks;
    00725       } else {
    00726         switch (v->type) {
    00727           case VEH_TRAIN:    ticks = Train::From(v)->wait_counter; break;
    00728           case VEH_AIRCRAFT: ticks = Aircraft::From(v)->turn_counter; break;
    00729           default:           ticks = 0; break;
    00730         }
    00731       }
    00732       return (variable - 0x80) == 0x10 ? ticks : GB(ticks, 8, 8);
    00733     }
    00734     case 0x12: return max(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
    00735     case 0x13: return GB(max(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0), 8, 8);
    00736     case 0x14: return v->service_interval;
    00737     case 0x15: return GB(v->service_interval, 8, 8);
    00738     case 0x16: return v->last_station_visited;
    00739     case 0x17: return v->tick_counter;
    00740     case 0x18: return v->max_speed;
    00741     case 0x19: return GB(v->max_speed, 8, 8);
    00742     case 0x1A: return v->x_pos;
    00743     case 0x1B: return GB(v->x_pos, 8, 8);
    00744     case 0x1C: return v->y_pos;
    00745     case 0x1D: return GB(v->y_pos, 8, 8);
    00746     case 0x1E: return v->z_pos;
    00747     case 0x1F: return object->u.vehicle.info_view ? DIR_W : v->direction;
    00748     case 0x28: return v->cur_image;
    00749     case 0x29: return GB(v->cur_image, 8, 8);
    00750     case 0x32: return v->vehstatus;
    00751     case 0x33: return 0; // non-existent high byte of vehstatus
    00752     case 0x34: return v->cur_speed;
    00753     case 0x35: return GB(v->cur_speed, 8, 8);
    00754     case 0x36: return v->subspeed;
    00755     case 0x37: return v->acceleration;
    00756     case 0x39: return v->cargo_type;
    00757     case 0x3A: return v->cargo_cap;
    00758     case 0x3B: return GB(v->cargo_cap, 8, 8);
    00759     case 0x3C: return v->cargo.Count();
    00760     case 0x3D: return GB(v->cargo.Count(), 8, 8);
    00761     case 0x3E: return v->cargo.Source();
    00762     case 0x3F: return v->cargo.DaysInTransit();
    00763     case 0x40: return v->age;
    00764     case 0x41: return GB(v->age, 8, 8);
    00765     case 0x42: return v->max_age;
    00766     case 0x43: return GB(v->max_age, 8, 8);
    00767     case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
    00768     case 0x45: return v->unitnumber;
    00769     case 0x46: return Engine::Get(v->engine_type)->internal_id;
    00770     case 0x47: return GB(Engine::Get(v->engine_type)->internal_id, 8, 8);
    00771     case 0x48:
    00772       if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
    00773       return HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
    00774
    00775     case 0x49: return v->day_counter;
    00776     case 0x4A: return v->breakdowns_since_last_service;
    00777     case 0x4B: return v->breakdown_ctr;
    00778     case 0x4C: return v->breakdown_delay;
    00779     case 0x4D: return v->breakdown_chance;
    00780     case 0x4E: return v->reliability;
    00781     case 0x4F: return GB(v->reliability, 8, 8);
    00782     case 0x50: return v->reliability_spd_dec;
    00783     case 0x51: return GB(v->reliability_spd_dec, 8, 8);
    00784     case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
    00785     case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()),  8, 24);
    00786     case 0x54: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 16, 16);
    00787     case 0x55: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 24,  8);
    00788     case 0x56: return ClampToI32(v->GetDisplayProfitLastYear());
    00789     case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()),  8, 24);
    00790     case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
    00791     case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24,  8);
    00792     case 0x5A: return v->Next() == NULL ? INVALID_VEHICLE : v->Next()->index;
    00793     case 0x5C: return ClampToI32(v->value);
    00794     case 0x5D: return GB(ClampToI32(v->value),  8, 24);
    00795     case 0x5E: return GB(ClampToI32(v->value), 16, 16);
    00796     case 0x5F: return GB(ClampToI32(v->value), 24,  8);
    00797     case 0x72: return v->cargo_subtype;
    00798     case 0x7A: return v->random_bits;
    00799     case 0x7B: return v->waiting_triggers;
    00800   }
    00801
    00802   /* Vehicle specific properties */
    00803   switch (v->type) {
    00804     case VEH_TRAIN: {
    00805       Train *t = Train::From(v);
    00806       switch (variable - 0x80) {
    00807         case 0x62: return t->track;
    00808         case 0x66: return t->railtype;
    00809         case 0x73: return t->tcache.cached_veh_length;
    00810         case 0x74: return t->tcache.cached_power;
    00811         case 0x75: return GB(t->tcache.cached_power,  8, 24);
    00812         case 0x76: return GB(t->tcache.cached_power, 16, 16);
    00813         case 0x77: return GB(t->tcache.cached_power, 24,  8);
    00814         case 0x7C: return t->First()->index;
    00815         case 0x7D: return GB(t->First()->index, 8, 8);
    00816         case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
    00817       }
    00818     } break;
    00819
    00820     case VEH_ROAD: {
    00821       RoadVehicle *rv = RoadVehicle::From(v);
    00822       switch (variable - 0x80) {
    00823         case 0x62: return rv->state;
    00824         case 0x64: return rv->blocked_ctr;
    00825         case 0x65: return GB(rv->blocked_ctr, 8, 8);
    00826         case 0x66: return rv->overtaking;
    00827         case 0x67: return rv->overtaking_ctr;
    00828         case 0x68: return rv->crashed_ctr;
    00829         case 0x69: return GB(rv->crashed_ctr, 8, 8);
    00830       }
    00831     } break;
    00832
    00833     case VEH_AIRCRAFT: {
    00834       Aircraft *a = Aircraft::From(v);
    00835       switch (variable - 0x80) {
    00836         case 0x62: return MapAircraftMovementState(a);  // Current movement state
    00837         case 0x63: return a->targetairport;             // Airport to which the action refers
    00838         case 0x66: return MapAircraftMovementAction(a); // Current movement action
    00839       }
    00840     } break;
    00841
    00842     default: break;
    00843   }
    00844
    00845   DEBUG(grf, 1, "Unhandled vehicle property 0x%X, type 0x%X", variable, (uint)v->type);
    00846
    00847   *available = false;
    00848   return UINT_MAX;
    00849 }
    00850
    00851
    00852 static const SpriteGroup *VehicleResolveReal(const ResolverObject *object, const RealSpriteGroup *group)
    00853 {
    00854   const Vehicle *v = object->u.vehicle.self;
    00855
    00856   if (v == NULL) {
    00857     if (group->num_loading > 0) return group->loading[0];
    00858     if (group->num_loaded  > 0) return group->loaded[0];
    00859     return NULL;
    00860   }
    00861
    00862   bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
    00863
    00864   uint totalsets = in_motion ? group->num_loaded : group->num_loading;
    00865
    00866   uint set = (v->cargo.Count() * totalsets) / max((uint16)1, v->cargo_cap);
    00867   set = min(set, totalsets - 1);
    00868
    00869   return in_motion ? group->loaded[set] : group->loading[set];
    00870 }
    00871
    00872
    00873 static inline void NewVehicleResolver(ResolverObject *res, EngineID engine_type, const Vehicle *v)
    00874 {
    00875   res->GetRandomBits = &VehicleGetRandomBits;
    00876   res->GetTriggers   = &VehicleGetTriggers;
    00877   res->SetTriggers   = &VehicleSetTriggers;
    00878   res->GetVariable   = &VehicleGetVariable;
    00879   res->ResolveReal   = &VehicleResolveReal;
    00880
    00881   res->u.vehicle.self   = v;
    00882   res->u.vehicle.parent = (v != NULL) ? v->First() : v;
    00883
    00884   res->u.vehicle.self_type = engine_type;
    00885   res->u.vehicle.info_view = false;
    00886
    00887   res->callback        = CBID_NO_CALLBACK;
    00888   res->callback_param1 = 0;
    00889   res->callback_param2 = 0;
    00890   res->last_value      = 0;
    00891   res->trigger         = 0;
    00892   res->reseed          = 0;
    00893   res->count           = 0;
    00894
    00895   const Engine *e = Engine::Get(engine_type);
    00896   res->grffile         = (e != NULL ? e->grffile : NULL);
    00897 }
    00898
    00899
    00908 static const SpriteGroup *GetVehicleSpriteGroup(EngineID engine, const Vehicle *v, bool use_cache = true)
    00909 {
    00910   const SpriteGroup *group;
    00911   CargoID cargo;
    00912
    00913   if (v == NULL) {
    00914     cargo = CT_PURCHASE;
    00915   } else {
    00916     cargo = v->cargo_type;
    00917
    00918     if (v->type == VEH_TRAIN) {
    00919       /* We always use cached value, except for callbacks because the override spriteset
    00920        * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
    00921        * as v->cargo_type is temporary changed to the new type */
    00922       group = use_cache ? Train::From(v)->tcache.cached_override : GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, Train::From(v)->tcache.first_engine);
    00923       if (group != NULL) return group;
    00924     } else if (v->type == VEH_ROAD) {
    00925       group = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, RoadVehicle::From(v)->rcache.first_engine);
    00926       if (group != NULL) return group;
    00927     }
    00928   }
    00929
    00930   const Engine *e = Engine::Get(engine);
    00931
    00932   assert(cargo < lengthof(e->group));
    00933   group = e->group[cargo];
    00934   if (group != NULL) return group;
    00935
    00936   /* Fall back to the default set if the selected cargo type is not defined */
    00937   return e->group[CT_DEFAULT];
    00938 }
    00939
    00940
    00941 SpriteID GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction)
    00942 {
    00943   const SpriteGroup *group;
    00944   ResolverObject object;
    00945
    00946   NewVehicleResolver(&object, engine, v);
    00947
    00948   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v), &object);
    00949   if (group == NULL || group->GetNumResults() == 0) return 0;
    00950
    00951   return group->GetResult() + (direction % group->GetNumResults());
    00952 }
    00953
    00954
    00955 SpriteID GetRotorOverrideSprite(EngineID engine, const Aircraft *v, bool info_view)
    00956 {
    00957   const Engine *e = Engine::Get(engine);
    00958
    00959   /* Only valid for helicopters */
    00960   assert(e->type == VEH_AIRCRAFT);
    00961   assert(!(e->u.air.subtype & AIR_CTOL));
    00962
    00963   ResolverObject object;
    00964
    00965   NewVehicleResolver(&object, engine, v);
    00966
    00967   object.u.vehicle.info_view = info_view;
    00968
    00969   const SpriteGroup *group = GetWagonOverrideSpriteSet(engine, CT_DEFAULT, engine);
    00970   group = SpriteGroup::Resolve(group, &object);
    00971
    00972   if (group == NULL || group->GetNumResults() == 0) return 0;
    00973
    00974   if (v == NULL) return group->GetResult();
    00975
    00976   return group->GetResult() + (info_view ? 0 : (v->Next()->Next()->state % group->GetNumResults()));
    00977 }
    00978
    00979
    00985 bool UsesWagonOverride(const Vehicle *v)
    00986 {
    00987   assert(v->type == VEH_TRAIN);
    00988   return Train::From(v)->tcache.cached_override != NULL;
    00989 }
    00990
    01000 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
    01001 {
    01002   const SpriteGroup *group;
    01003   ResolverObject object;
    01004
    01005   NewVehicleResolver(&object, engine, v);
    01006
    01007   object.callback        = callback;
    01008   object.callback_param1 = param1;
    01009   object.callback_param2 = param2;
    01010
    01011   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
    01012   if (group == NULL) return CALLBACK_FAILED;
    01013
    01014   return group->GetCallbackResult();
    01015 }
    01016
    01027 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
    01028 {
    01029   const SpriteGroup *group;
    01030   ResolverObject object;
    01031
    01032   NewVehicleResolver(&object, engine, v);
    01033
    01034   object.callback        = callback;
    01035   object.callback_param1 = param1;
    01036   object.callback_param2 = param2;
    01037
    01038   object.u.vehicle.parent = parent;
    01039
    01040   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(engine, v, false), &object);
    01041   if (group == NULL) return CALLBACK_FAILED;
    01042
    01043   return group->GetCallbackResult();
    01044 }
    01045
    01046
    01047 /* Callback 36 handlers */
    01048 uint GetVehicleProperty(const Vehicle *v, PropertyID property, uint orig_value)
    01049 {
    01050   uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, v->engine_type, v);
    01051   if (callback != CALLBACK_FAILED) return callback;
    01052
    01053   return orig_value;
    01054 }
    01055
    01056
    01057 uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value)
    01058 {
    01059   uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, engine, NULL);
    01060   if (callback != CALLBACK_FAILED) return callback;
    01061
    01062   return orig_value;
    01063 }
    01064
    01065
    01066 static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
    01067 {
    01068   const SpriteGroup *group;
    01069   ResolverObject object;
    01070   byte new_random_bits;
    01071
    01072   /* We can't trigger a non-existent vehicle... */
    01073   assert(v != NULL);
    01074
    01075   NewVehicleResolver(&object, v->engine_type, v);
    01076   object.callback = CBID_RANDOM_TRIGGER;
    01077   object.trigger = trigger;
    01078
    01079   group = SpriteGroup::Resolve(GetVehicleSpriteGroup(v->engine_type, v), &object);
    01080   if (group == NULL) return;
    01081
    01082   new_random_bits = Random();
    01083   v->random_bits &= ~object.reseed;
    01084   v->random_bits |= (first ? new_random_bits : base_random_bits) & object.reseed;
    01085
    01086   switch (trigger) {
    01087     case VEHICLE_TRIGGER_NEW_CARGO:
    01088       /* All vehicles in chain get ANY_NEW_CARGO trigger now.
    01089        * So we call it for the first one and they will recurse.
    01090        * Indexing part of vehicle random bits needs to be
    01091        * same for all triggered vehicles in the chain (to get
    01092        * all the random-cargo wagons carry the same cargo,
    01093        * i.e.), so we give them all the NEW_CARGO triggered
    01094        * vehicle's portion of random bits. */
    01095       assert(first);
    01096       DoTriggerVehicle(v->First(), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
    01097       break;
    01098
    01099     case VEHICLE_TRIGGER_DEPOT:
    01100       /* We now trigger the next vehicle in chain recursively.
    01101        * The random bits portions may be different for each
    01102        * vehicle in chain. */
    01103       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, 0, true);
    01104       break;
    01105
    01106     case VEHICLE_TRIGGER_EMPTY:
    01107       /* We now trigger the next vehicle in chain
    01108        * recursively.  The random bits portions must be same
    01109        * for each vehicle in chain, so we give them all
    01110        * first chained vehicle's portion of random bits. */
    01111       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
    01112       break;
    01113
    01114     case VEHICLE_TRIGGER_ANY_NEW_CARGO:
    01115       /* Now pass the trigger recursively to the next vehicle
    01116        * in chain. */
    01117       assert(!first);
    01118       if (v->Next() != NULL) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
    01119       break;
    01120
    01121     case VEHICLE_TRIGGER_CALLBACK_32:
    01122       /* Do not do any recursion */
    01123       break;
    01124   }
    01125 }
    01126
    01127 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
    01128 {
    01129   if (trigger == VEHICLE_TRIGGER_DEPOT) {
    01130     /* store that the vehicle entered a depot this tick */
    01131     VehicleEnteredDepotThisTick(v);
    01132   }
    01133
    01134   v->InvalidateNewGRFCacheOfChain();
    01135   DoTriggerVehicle(v, trigger, 0, true);
    01136   v->InvalidateNewGRFCacheOfChain();
    01137 }
    01138
    01139 /* Functions for changing the order of vehicle purchase lists
    01140  * This is currently only implemented for rail vehicles. */
    01141
    01148 uint ListPositionOfEngine(EngineID engine)
    01149 {
    01150   const Engine *e = Engine::Get(engine);
    01151   if (e->grffile == NULL) return e->list_position;
    01152
    01153   /* Crude sorting to group by GRF ID */
    01154   return (e->grffile->grfid * 256) + e->list_position;
    01155 }
    01156
    01157 struct ListOrderChange {
    01158   EngineID engine;
    01159   EngineID target;
    01160 };
    01161
    01162 static SmallVector<ListOrderChange, 16> _list_order_changes;
    01163
    01164 void AlterVehicleListOrder(EngineID engine, EngineID target)
    01165 {
    01166   /* Add the list order change to a queue */
    01167   ListOrderChange *loc = _list_order_changes.Append();
    01168   loc->engine = engine;
    01169   loc->target = target;
    01170 }
    01171
    01172 void CommitVehicleListOrderChanges()
    01173 {
    01174   /* List position to Engine map */
    01175   typedef SmallMap<uint16, Engine *, 16> ListPositionMap;
    01176   ListPositionMap lptr_map;
    01177
    01178   const ListOrderChange *end = _list_order_changes.End();
    01179   for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) {
    01180     EngineID engine = it->engine;
    01181     EngineID target = it->target;
    01182
    01183     if (engine == target) continue;
    01184
    01185     Engine *source_e = Engine::Get(engine);
    01186     Engine *target_e = NULL;
    01187
    01188     /* Populate map with current list positions */
    01189     Engine *e;
    01190     FOR_ALL_ENGINES_OF_TYPE(e, source_e->type) {
    01191       if (!_settings_game.vehicle.dynamic_engines || e->grffile == source_e->grffile) {
    01192         if (e->internal_id == target) target_e = e;
    01193         lptr_map[e->list_position] = e;
    01194       }
    01195     }
    01196
    01197     /* std::map sorted by default, SmallMap does not */
    01198     lptr_map.SortByKey();
    01199
    01200     /* Get the target position, if it exists */
    01201     if (target_e != NULL) {
    01202       uint16 target_position = target_e->list_position;
    01203
    01204       bool moving = false;
    01205       const ListPositionMap::Pair *end = lptr_map.End();
    01206       for (ListPositionMap::Pair *it = lptr_map.Begin(); it != end; ++it) {
    01207         if (it->first == target_position) moving = true;
    01208         if (moving) it->second->list_position++;
    01209       }
    01210
    01211       source_e->list_position = target_position;
    01212     }
    01213
    01214     lptr_map.Clear();
    01215   }
    01216
    01217   /* Clear out the queue */
    01218   _list_order_changes.Reset();
    01219 }