newgrf_engine.cpp

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

Generated on Thu Jan 8 19:01:40 2009 for openttd by  doxygen 1.5.6