# newgrf_engine.cpp

Go to the documentation of this file.

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