newgrf_engine.cpp

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