(svn r28004) -Update from Eints:
[openttd.git] / src / newgrf_engine.cpp
blob660b7e476b404fa62baa33401230ca91d238c450
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file newgrf_engine.cpp NewGRF handling of engines. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "train.h"
15 #include "roadveh.h"
16 #include "company_func.h"
17 #include "newgrf_cargo.h"
18 #include "newgrf_spritegroup.h"
19 #include "date_func.h"
20 #include "vehicle_func.h"
21 #include "core/random_func.hpp"
22 #include "aircraft.h"
23 #include "station_base.h"
24 #include "company_base.h"
25 #include "newgrf_railtype.h"
26 #include "ship.h"
28 #include "safeguards.h"
30 struct WagonOverride {
31 EngineID *train_id;
32 uint trains;
33 CargoID cargo;
34 const SpriteGroup *group;
37 void SetWagonOverrideSprites(EngineID engine, CargoID cargo, const SpriteGroup *group, EngineID *train_id, uint trains)
39 Engine *e = Engine::Get(engine);
40 WagonOverride *wo;
42 assert(cargo < NUM_CARGO + 2); // Include CT_DEFAULT and CT_PURCHASE pseudo cargoes.
44 e->overrides_count++;
45 e->overrides = ReallocT(e->overrides, e->overrides_count);
47 wo = &e->overrides[e->overrides_count - 1];
48 wo->group = group;
49 wo->cargo = cargo;
50 wo->trains = trains;
51 wo->train_id = MallocT<EngineID>(trains);
52 memcpy(wo->train_id, train_id, trains * sizeof *train_id);
55 const SpriteGroup *GetWagonOverrideSpriteSet(EngineID engine, CargoID cargo, EngineID overriding_engine)
57 const Engine *e = Engine::Get(engine);
59 for (uint i = 0; i < e->overrides_count; i++) {
60 const WagonOverride *wo = &e->overrides[i];
62 if (wo->cargo != cargo && wo->cargo != CT_DEFAULT) continue;
64 for (uint j = 0; j < wo->trains; j++) {
65 if (wo->train_id[j] == overriding_engine) return wo->group;
68 return NULL;
71 /**
72 * Unload all wagon override sprite groups.
74 void UnloadWagonOverrides(Engine *e)
76 for (uint i = 0; i < e->overrides_count; i++) {
77 WagonOverride *wo = &e->overrides[i];
78 free(wo->train_id);
80 free(e->overrides);
81 e->overrides_count = 0;
82 e->overrides = NULL;
86 void SetCustomEngineSprites(EngineID engine, byte cargo, const SpriteGroup *group)
88 Engine *e = Engine::Get(engine);
89 assert(cargo < lengthof(e->grf_prop.spritegroup));
91 if (e->grf_prop.spritegroup[cargo] != NULL) {
92 grfmsg(6, "SetCustomEngineSprites: engine %d cargo %d already has group -- replacing", engine, cargo);
94 e->grf_prop.spritegroup[cargo] = group;
98 /**
99 * Tie a GRFFile entry to an engine, to allow us to retrieve GRF parameters
100 * etc during a game.
101 * @param engine Engine ID to tie the GRFFile to.
102 * @param file Pointer of GRFFile to tie.
104 void SetEngineGRF(EngineID engine, const GRFFile *file)
106 Engine *e = Engine::Get(engine);
107 e->grf_prop.grffile = file;
111 static int MapOldSubType(const Vehicle *v)
113 switch (v->type) {
114 case VEH_TRAIN:
115 if (Train::From(v)->IsEngine()) return 0;
116 if (Train::From(v)->IsFreeWagon()) return 4;
117 return 2;
118 case VEH_ROAD:
119 case VEH_SHIP: return 0;
120 case VEH_AIRCRAFT:
121 case VEH_DISASTER: return v->subtype;
122 case VEH_EFFECT: return v->subtype << 1;
123 default: NOT_REACHED();
128 /* TTDP style aircraft movement states for GRF Action 2 Var 0xE2 */
129 enum TTDPAircraftMovementStates {
130 AMS_TTDP_HANGAR,
131 AMS_TTDP_TO_HANGAR,
132 AMS_TTDP_TO_PAD1,
133 AMS_TTDP_TO_PAD2,
134 AMS_TTDP_TO_PAD3,
135 AMS_TTDP_TO_ENTRY_2_AND_3,
136 AMS_TTDP_TO_ENTRY_2_AND_3_AND_H,
137 AMS_TTDP_TO_JUNCTION,
138 AMS_TTDP_LEAVE_RUNWAY,
139 AMS_TTDP_TO_INWAY,
140 AMS_TTDP_TO_RUNWAY,
141 AMS_TTDP_TO_OUTWAY,
142 AMS_TTDP_WAITING,
143 AMS_TTDP_TAKEOFF,
144 AMS_TTDP_TO_TAKEOFF,
145 AMS_TTDP_CLIMBING,
146 AMS_TTDP_FLIGHT_APPROACH,
147 AMS_TTDP_UNUSED_0x11,
148 AMS_TTDP_FLIGHT_TO_TOWER,
149 AMS_TTDP_UNUSED_0x13,
150 AMS_TTDP_FLIGHT_FINAL,
151 AMS_TTDP_FLIGHT_DESCENT,
152 AMS_TTDP_BRAKING,
153 AMS_TTDP_HELI_TAKEOFF_AIRPORT,
154 AMS_TTDP_HELI_TO_TAKEOFF_AIRPORT,
155 AMS_TTDP_HELI_LAND_AIRPORT,
156 AMS_TTDP_HELI_TAKEOFF_HELIPORT,
157 AMS_TTDP_HELI_TO_TAKEOFF_HELIPORT,
158 AMS_TTDP_HELI_LAND_HELIPORT,
163 * Map OTTD aircraft movement states to TTDPatch style movement states
164 * (VarAction 2 Variable 0xE2)
166 static byte MapAircraftMovementState(const Aircraft *v)
168 const Station *st = GetTargetAirportIfValid(v);
169 if (st == NULL) return AMS_TTDP_FLIGHT_TO_TOWER;
171 const AirportFTAClass *afc = st->airport.GetFTA();
172 uint16 amdflag = afc->MovingData(v->pos)->flag;
174 switch (v->state) {
175 case HANGAR:
176 /* The international airport is a special case as helicopters can land in
177 * front of the hangar. Helicopters also change their air.state to
178 * AMED_HELI_LOWER some time before actually descending. */
180 /* This condition only occurs for helicopters, during descent,
181 * to a landing by the hangar of an international airport. */
182 if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT;
184 /* This condition only occurs for helicopters, before starting descent,
185 * to a landing by the hangar of an international airport. */
186 if (amdflag & AMED_SLOWTURN) return AMS_TTDP_FLIGHT_TO_TOWER;
188 /* The final two conditions apply to helicopters or aircraft.
189 * Has reached hangar? */
190 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_HANGAR;
192 /* Still moving towards hangar. */
193 return AMS_TTDP_TO_HANGAR;
195 case TERM1:
196 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD1;
197 return AMS_TTDP_TO_JUNCTION;
199 case TERM2:
200 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD2;
201 return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
203 case TERM3:
204 case TERM4:
205 case TERM5:
206 case TERM6:
207 case TERM7:
208 case TERM8:
209 /* TTDPatch only has 3 terminals, so treat these states the same */
210 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD3;
211 return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
213 case HELIPAD1:
214 case HELIPAD2:
215 case HELIPAD3:
216 /* Will only occur for helicopters.*/
217 if (amdflag & AMED_HELI_LOWER) return AMS_TTDP_HELI_LAND_AIRPORT; // Descending.
218 if (amdflag & AMED_SLOWTURN) return AMS_TTDP_FLIGHT_TO_TOWER; // Still hasn't started descent.
219 return AMS_TTDP_TO_JUNCTION; // On the ground.
221 case TAKEOFF: // Moving to takeoff position.
222 return AMS_TTDP_TO_OUTWAY;
224 case STARTTAKEOFF: // Accelerating down runway.
225 return AMS_TTDP_TAKEOFF;
227 case ENDTAKEOFF: // Ascent
228 return AMS_TTDP_CLIMBING;
230 case HELITAKEOFF: // Helicopter is moving to take off position.
231 if (afc->delta_z == 0) {
232 return amdflag & AMED_HELI_RAISE ?
233 AMS_TTDP_HELI_TAKEOFF_AIRPORT : AMS_TTDP_TO_JUNCTION;
234 } else {
235 return AMS_TTDP_HELI_TAKEOFF_HELIPORT;
238 case FLYING:
239 return amdflag & AMED_HOLD ? AMS_TTDP_FLIGHT_APPROACH : AMS_TTDP_FLIGHT_TO_TOWER;
241 case LANDING: // Descent
242 return AMS_TTDP_FLIGHT_DESCENT;
244 case ENDLANDING: // On the runway braking
245 if (amdflag & AMED_BRAKE) return AMS_TTDP_BRAKING;
246 /* Landed - moving off runway */
247 return AMS_TTDP_TO_INWAY;
249 case HELILANDING:
250 case HELIENDLANDING: // Helicoptor is decending.
251 if (amdflag & AMED_HELI_LOWER) {
252 return afc->delta_z == 0 ?
253 AMS_TTDP_HELI_LAND_AIRPORT : AMS_TTDP_HELI_LAND_HELIPORT;
254 } else {
255 return AMS_TTDP_FLIGHT_TO_TOWER;
258 default:
259 return AMS_TTDP_HANGAR;
264 /* TTDP style aircraft movement action for GRF Action 2 Var 0xE6 */
265 enum TTDPAircraftMovementActions {
266 AMA_TTDP_IN_HANGAR,
267 AMA_TTDP_ON_PAD1,
268 AMA_TTDP_ON_PAD2,
269 AMA_TTDP_ON_PAD3,
270 AMA_TTDP_HANGAR_TO_PAD1,
271 AMA_TTDP_HANGAR_TO_PAD2,
272 AMA_TTDP_HANGAR_TO_PAD3,
273 AMA_TTDP_LANDING_TO_PAD1,
274 AMA_TTDP_LANDING_TO_PAD2,
275 AMA_TTDP_LANDING_TO_PAD3,
276 AMA_TTDP_PAD1_TO_HANGAR,
277 AMA_TTDP_PAD2_TO_HANGAR,
278 AMA_TTDP_PAD3_TO_HANGAR,
279 AMA_TTDP_PAD1_TO_TAKEOFF,
280 AMA_TTDP_PAD2_TO_TAKEOFF,
281 AMA_TTDP_PAD3_TO_TAKEOFF,
282 AMA_TTDP_HANGAR_TO_TAKOFF,
283 AMA_TTDP_LANDING_TO_HANGAR,
284 AMA_TTDP_IN_FLIGHT,
289 * Map OTTD aircraft movement states to TTDPatch style movement actions
290 * (VarAction 2 Variable 0xE6)
291 * This is not fully supported yet but it's enough for Planeset.
293 static byte MapAircraftMovementAction(const Aircraft *v)
295 switch (v->state) {
296 case HANGAR:
297 return (v->cur_speed > 0) ? AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_IN_HANGAR;
299 case TERM1:
300 case HELIPAD1:
301 return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD1 : AMA_TTDP_LANDING_TO_PAD1;
303 case TERM2:
304 case HELIPAD2:
305 return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD2 : AMA_TTDP_LANDING_TO_PAD2;
307 case TERM3:
308 case TERM4:
309 case TERM5:
310 case TERM6:
311 case TERM7:
312 case TERM8:
313 case HELIPAD3:
314 return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD3 : AMA_TTDP_LANDING_TO_PAD3;
316 case TAKEOFF: // Moving to takeoff position
317 case STARTTAKEOFF: // Accelerating down runway
318 case ENDTAKEOFF: // Ascent
319 case HELITAKEOFF:
320 /* @todo Need to find which terminal (or hangar) we've come from. How? */
321 return AMA_TTDP_PAD1_TO_TAKEOFF;
323 case FLYING:
324 return AMA_TTDP_IN_FLIGHT;
326 case LANDING: // Descent
327 case ENDLANDING: // On the runway braking
328 case HELILANDING:
329 case HELIENDLANDING:
330 /* @todo Need to check terminal we're landing to. Is it known yet? */
331 return (v->current_order.IsType(OT_GOTO_DEPOT)) ?
332 AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_LANDING_TO_PAD1;
334 default:
335 return AMA_TTDP_IN_HANGAR;
340 /* virtual */ uint32 VehicleScopeResolver::GetRandomBits() const
342 return this->v == NULL ? 0 : this->v->random_bits;
345 /* virtual */ uint32 VehicleScopeResolver::GetTriggers() const
347 return this->v == NULL ? 0 : this->v->waiting_triggers;
351 /* virtual */ ScopeResolver *VehicleResolverObject::GetScope(VarSpriteGroupScope scope, byte relative)
353 switch (scope) {
354 case VSG_SCOPE_SELF: return &this->self_scope;
355 case VSG_SCOPE_PARENT: return &this->parent_scope;
356 case VSG_SCOPE_RELATIVE: {
357 int32 count = GB(relative, 0, 4);
358 if (this->self_scope.v != NULL && (relative != this->cached_relative_count || count == 0)) {
359 /* Note: This caching only works as long as the VSG_SCOPE_RELATIVE cannot be used in
360 * VarAct2 with procedure calls. */
361 if (count == 0) count = GetRegister(0x100);
363 const Vehicle *v = NULL;
364 switch (GB(relative, 6, 2)) {
365 default: NOT_REACHED();
366 case 0x00: // count back (away from the engine), starting at this vehicle
367 v = this->self_scope.v;
368 break;
369 case 0x01: // count forward (toward the engine), starting at this vehicle
370 v = this->self_scope.v;
371 count = -count;
372 break;
373 case 0x02: // count back, starting at the engine
374 v = this->parent_scope.v;
375 break;
376 case 0x03: { // count back, starting at the first vehicle in this chain of vehicles with the same ID, as for vehicle variable 41
377 const Vehicle *self = this->self_scope.v;
378 for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
379 if (u->engine_type != self->engine_type) {
380 v = NULL;
381 } else {
382 if (v == NULL) v = u;
385 if (v == NULL) v = self;
386 break;
389 this->relative_scope.SetVehicle(v->Move(count));
391 return &this->relative_scope;
393 default: return ResolverObject::GetScope(scope, relative);
398 * Determines the livery of an engine.
400 * This always uses dual company colours independent of GUI settings. So it is desync-safe.
402 * @param engine Engine type
403 * @param v Vehicle, NULL in purchase list.
404 * @return Livery to use
406 static const Livery *LiveryHelper(EngineID engine, const Vehicle *v)
408 const Livery *l;
410 if (v == NULL) {
411 if (!Company::IsValidID(_current_company)) return NULL;
412 l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL, LIT_ALL);
413 } else if (v->IsGroundVehicle()) {
414 l = GetEngineLivery(v->engine_type, v->owner, v->GetGroundVehicleCache()->first_engine, v, LIT_ALL);
415 } else {
416 l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v, LIT_ALL);
419 return l;
423 * Helper to get the position of a vehicle within a chain of vehicles.
424 * @param v the vehicle to get the position of.
425 * @param consecutive whether to look at the whole chain or the vehicles
426 * with the same 'engine type'.
427 * @return the position in the chain from front and tail and chain length.
429 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
431 const Vehicle *u;
432 byte chain_before = 0;
433 byte chain_after = 0;
435 for (u = v->First(); u != v; u = u->Next()) {
436 chain_before++;
437 if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
440 while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
441 chain_after++;
442 u = u->Next();
445 return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
448 static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object, byte variable, uint32 parameter, bool *available)
450 /* Calculated vehicle parameters */
451 switch (variable) {
452 case 0x25: // Get engine GRF ID
453 return v->GetGRFID();
455 case 0x40: // Get length of consist
456 if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_CONSIST_LENGTH)) {
457 v->grf_cache.position_consist_length = PositionHelper(v, false);
458 SetBit(v->grf_cache.cache_valid, NCVV_POSITION_CONSIST_LENGTH);
460 return v->grf_cache.position_consist_length;
462 case 0x41: // Get length of same consecutive wagons
463 if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_SAME_ID_LENGTH)) {
464 v->grf_cache.position_same_id_length = PositionHelper(v, true);
465 SetBit(v->grf_cache.cache_valid, NCVV_POSITION_SAME_ID_LENGTH);
467 return v->grf_cache.position_same_id_length;
469 case 0x42: { // Consist cargo information
470 if (!HasBit(v->grf_cache.cache_valid, NCVV_CONSIST_CARGO_INFORMATION)) {
471 const Vehicle *u;
472 byte cargo_classes = 0;
473 uint8 common_cargoes[NUM_CARGO];
474 uint8 common_subtypes[256];
475 byte user_def_data = 0;
476 CargoID common_cargo_type = CT_INVALID;
477 uint8 common_subtype = 0xFF; // Return 0xFF if nothing is carried
479 /* Reset our arrays */
480 memset(common_cargoes, 0, sizeof(common_cargoes));
481 memset(common_subtypes, 0, sizeof(common_subtypes));
483 for (u = v; u != NULL; u = u->Next()) {
484 if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
486 /* Skip empty engines */
487 if (!u->GetEngine()->CanCarryCargo()) continue;
489 cargo_classes |= CargoSpec::Get(u->cargo_type)->classes;
490 common_cargoes[u->cargo_type]++;
493 /* Pick the most common cargo type */
494 uint common_cargo_best_amount = 0;
495 for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
496 if (common_cargoes[cargo] > common_cargo_best_amount) {
497 common_cargo_best_amount = common_cargoes[cargo];
498 common_cargo_type = cargo;
502 /* Count subcargo types of common_cargo_type */
503 for (u = v; u != NULL; u = u->Next()) {
504 /* Skip empty engines and engines not carrying common_cargo_type */
505 if (u->cargo_type != common_cargo_type || !u->GetEngine()->CanCarryCargo()) continue;
507 common_subtypes[u->cargo_subtype]++;
510 /* Pick the most common subcargo type*/
511 uint common_subtype_best_amount = 0;
512 for (uint i = 0; i < lengthof(common_subtypes); i++) {
513 if (common_subtypes[i] > common_subtype_best_amount) {
514 common_subtype_best_amount = common_subtypes[i];
515 common_subtype = i;
519 /* Note: We have to store the untranslated cargotype in the cache as the cache can be read by different NewGRFs,
520 * which will need different translations */
521 v->grf_cache.consist_cargo_information = cargo_classes | (common_cargo_type << 8) | (common_subtype << 16) | (user_def_data << 24);
522 SetBit(v->grf_cache.cache_valid, NCVV_CONSIST_CARGO_INFORMATION);
525 /* The cargo translation is specific to the accessing GRF, and thus cannot be cached. */
526 CargoID common_cargo_type = (v->grf_cache.consist_cargo_information >> 8) & 0xFF;
528 /* Note:
529 * - Unlike everywhere else the cargo translation table is only used since grf version 8, not 7.
530 * - For translating the cargo type we need to use the GRF which is resolving the variable, which
531 * is object->ro.grffile.
532 * In case of CBID_TRAIN_ALLOW_WAGON_ATTACH this is not the same as v->GetGRF().
533 * - The grffile == NULL case only happens if this function is called for default vehicles.
534 * And this is only done by CheckCaches().
536 const GRFFile *grffile = object->ro.grffile;
537 uint8 common_bitnum = (common_cargo_type == CT_INVALID) ? 0xFF :
538 (grffile == NULL || grffile->grf_version < 8) ? CargoSpec::Get(common_cargo_type)->bitnum : grffile->cargo_map[common_cargo_type];
540 return (v->grf_cache.consist_cargo_information & 0xFFFF00FF) | common_bitnum << 8;
543 case 0x43: // Company information
544 if (!HasBit(v->grf_cache.cache_valid, NCVV_COMPANY_INFORMATION)) {
545 v->grf_cache.company_information = GetCompanyInfo(v->owner, LiveryHelper(v->engine_type, v));
546 SetBit(v->grf_cache.cache_valid, NCVV_COMPANY_INFORMATION);
548 return v->grf_cache.company_information;
550 case 0x44: // Aircraft information
551 if (v->type != VEH_AIRCRAFT || !Aircraft::From(v)->IsNormalAircraft()) return UINT_MAX;
554 const Vehicle *w = v->Next();
555 uint16 altitude = ClampToU16(v->z_pos - w->z_pos); // Aircraft height - shadow height
556 byte airporttype = ATP_TTDP_LARGE;
558 const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
560 if (st != NULL && st->airport.tile != INVALID_TILE) {
561 airporttype = st->airport.GetSpec()->ttd_airport_type;
564 return (Clamp(altitude, 0, 0xFF) << 8) | airporttype;
567 case 0x45: { // Curvature info
568 /* Format: xxxTxBxF
569 * F - previous wagon to current wagon, 0 if vehicle is first
570 * B - current wagon to next wagon, 0 if wagon is last
571 * T - previous wagon to next wagon, 0 in an S-bend
573 if (!v->IsGroundVehicle()) return 0;
575 const Vehicle *u_p = v->Previous();
576 const Vehicle *u_n = v->Next();
577 DirDiff f = (u_p == NULL) ? DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
578 DirDiff b = (u_n == NULL) ? DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
579 DirDiff t = ChangeDirDiff(f, b);
581 return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
582 ((b > DIRDIFF_REVERSE ? b | 8 : b) << 8) |
583 ( f > DIRDIFF_REVERSE ? f | 8 : f);
586 case 0x46: // Motion counter
587 return v->motion_counter;
589 case 0x47: { // Vehicle cargo info
590 /* Format: ccccwwtt
591 * tt - the cargo type transported by the vehicle,
592 * translated if a translation table has been installed.
593 * ww - cargo unit weight in 1/16 tons, same as cargo prop. 0F.
594 * cccc - the cargo class value of the cargo transported by the vehicle.
596 const CargoSpec *cs = CargoSpec::Get(v->cargo_type);
598 /* Note:
599 * For translating the cargo type we need to use the GRF which is resolving the variable, which
600 * is object->ro.grffile.
601 * In case of CBID_TRAIN_ALLOW_WAGON_ATTACH this is not the same as v->GetGRF().
603 return (cs->classes << 16) | (cs->weight << 8) | object->ro.grffile->cargo_map[v->cargo_type];
606 case 0x48: return v->GetEngine()->flags; // Vehicle Type Info
607 case 0x49: return v->build_year;
609 case 0x4A: {
610 if (v->type != VEH_TRAIN) return 0;
611 RailType rt = GetTileRailType(v->tile);
612 return (HasPowerOnRail(Train::From(v)->railtype, rt) ? 0x100 : 0) | GetReverseRailTypeTranslation(rt, object->ro.grffile);
615 case 0x4B: // Long date of last service
616 return v->date_of_last_service;
618 case 0x4C: // Current maximum speed in NewGRF units
619 if (!v->IsPrimaryVehicle()) return 0;
620 return v->GetCurrentMaxSpeed();
622 case 0x4D: // Position within articulated vehicle
623 if (!HasBit(v->grf_cache.cache_valid, NCVV_POSITION_IN_VEHICLE)) {
624 byte artic_before = 0;
625 for (const Vehicle *u = v; u->IsArticulatedPart(); u = u->Previous()) artic_before++;
626 byte artic_after = 0;
627 for (const Vehicle *u = v; u->HasArticulatedPart(); u = u->Next()) artic_after++;
628 v->grf_cache.position_in_vehicle = artic_before | artic_after << 8;
629 SetBit(v->grf_cache.cache_valid, NCVV_POSITION_IN_VEHICLE);
631 return v->grf_cache.position_in_vehicle;
633 /* Variables which use the parameter */
634 case 0x60: // Count consist's engine ID occurrence
635 if (v->type != VEH_TRAIN) return v->GetEngine()->grf_prop.local_id == parameter ? 1 : 0;
638 uint count = 0;
639 for (; v != NULL; v = v->Next()) {
640 if (v->GetEngine()->grf_prop.local_id == parameter) count++;
642 return count;
645 case 0x61: // Get variable of n-th vehicle in chain [signed number relative to vehicle]
646 if (!v->IsGroundVehicle() || parameter == 0x61) {
647 /* Not available */
648 break;
651 /* Only allow callbacks that don't change properties to avoid circular dependencies. */
652 if (object->ro.callback == CBID_NO_CALLBACK || object->ro.callback == CBID_RANDOM_TRIGGER || object->ro.callback == CBID_TRAIN_ALLOW_WAGON_ATTACH ||
653 object->ro.callback == CBID_VEHICLE_START_STOP_CHECK || object->ro.callback == CBID_VEHICLE_32DAY_CALLBACK || object->ro.callback == CBID_VEHICLE_COLOUR_MAPPING ||
654 object->ro.callback == CBID_VEHICLE_SPAWN_VISUAL_EFFECT) {
655 Vehicle *u = v->Move((int32)GetRegister(0x10F));
656 if (u == NULL) return 0; // available, but zero
658 if (parameter == 0x5F) {
659 /* This seems to be the only variable that makes sense to access via var 61, but is not handled by VehicleGetVariable */
660 return (u->random_bits << 8) | u->waiting_triggers;
661 } else {
662 return VehicleGetVariable(u, object, parameter, GetRegister(0x10E), available);
665 /* Not available */
666 break;
668 case 0x62: { // Curvature/position difference for n-th vehicle in chain [signed number relative to vehicle]
669 /* Format: zzyyxxFD
670 * zz - Signed difference of z position between the selected and this vehicle.
671 * yy - Signed difference of y position between the selected and this vehicle.
672 * xx - Signed difference of x position between the selected and this vehicle.
673 * F - Flags, bit 7 corresponds to VS_HIDDEN.
674 * D - Dir difference, like in 0x45.
676 if (!v->IsGroundVehicle()) return 0;
678 const Vehicle *u = v->Move((int8)parameter);
679 if (u == NULL) return 0;
681 /* Get direction difference. */
682 bool prev = (int8)parameter < 0;
683 uint32 ret = prev ? DirDifference(u->direction, v->direction) : DirDifference(v->direction, u->direction);
684 if (ret > DIRDIFF_REVERSE) ret |= 0x08;
686 if (u->vehstatus & VS_HIDDEN) ret |= 0x80;
688 /* Get position difference. */
689 ret |= ((prev ? u->x_pos - v->x_pos : v->x_pos - u->x_pos) & 0xFF) << 8;
690 ret |= ((prev ? u->y_pos - v->y_pos : v->y_pos - u->y_pos) & 0xFF) << 16;
691 ret |= ((prev ? u->z_pos - v->z_pos : v->z_pos - u->z_pos) & 0xFF) << 24;
693 return ret;
696 case 0xFE:
697 case 0xFF: {
698 uint16 modflags = 0;
700 if (v->type == VEH_TRAIN) {
701 const Train *t = Train::From(v);
702 bool is_powered_wagon = HasBit(t->flags, VRF_POWEREDWAGON);
703 const Train *u = is_powered_wagon ? t->First() : t; // for powered wagons the engine defines the type of engine (i.e. railtype)
704 RailType railtype = GetRailType(v->tile);
705 bool powered = t->IsEngine() || is_powered_wagon;
706 bool has_power = HasPowerOnRail(u->railtype, railtype);
708 if (powered && has_power) SetBit(modflags, 5);
709 if (powered && !has_power) SetBit(modflags, 6);
710 if (HasBit(t->flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
712 if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING)) SetBit(modflags, 1);
713 if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
715 return variable == 0xFE ? modflags : GB(modflags, 8, 8);
719 /* General vehicle properties */
720 switch (variable - 0x80) {
721 case 0x00: return v->type + 0x10;
722 case 0x01: return MapOldSubType(v);
723 case 0x04: return v->index;
724 case 0x05: return GB(v->index, 8, 8);
725 case 0x0A: return v->current_order.MapOldOrder();
726 case 0x0B: return v->current_order.GetDestination();
727 case 0x0C: return v->GetNumOrders();
728 case 0x0D: return v->cur_real_order_index;
729 case 0x10:
730 case 0x11: {
731 uint ticks;
732 if (v->current_order.IsType(OT_LOADING)) {
733 ticks = v->load_unload_ticks;
734 } else {
735 switch (v->type) {
736 case VEH_TRAIN: ticks = Train::From(v)->wait_counter; break;
737 case VEH_AIRCRAFT: ticks = Aircraft::From(v)->turn_counter; break;
738 default: ticks = 0; break;
741 return (variable - 0x80) == 0x10 ? ticks : GB(ticks, 8, 8);
743 case 0x12: return Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF);
744 case 0x13: return GB(Clamp(v->date_of_last_service - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
745 case 0x14: return v->GetServiceInterval();
746 case 0x15: return GB(v->GetServiceInterval(), 8, 8);
747 case 0x16: return v->last_station_visited;
748 case 0x17: return v->tick_counter;
749 case 0x18:
750 case 0x19: {
751 uint max_speed;
752 switch (v->type) {
753 case VEH_AIRCRAFT:
754 max_speed = Aircraft::From(v)->GetSpeedOldUnits(); // Convert to old units.
755 break;
757 default:
758 max_speed = v->vcache.cached_max_speed;
759 break;
761 return (variable - 0x80) == 0x18 ? max_speed : GB(max_speed, 8, 8);
763 case 0x1A: return v->x_pos;
764 case 0x1B: return GB(v->x_pos, 8, 8);
765 case 0x1C: return v->y_pos;
766 case 0x1D: return GB(v->y_pos, 8, 8);
767 case 0x1E: return v->z_pos;
768 case 0x1F: return object->info_view ? DIR_W : v->direction;
769 case 0x28: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
770 case 0x29: return 0; // cur_image is a potential desyncer due to Action1 in static NewGRFs.
771 case 0x32: return v->vehstatus;
772 case 0x33: return 0; // non-existent high byte of vehstatus
773 case 0x34: return v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed;
774 case 0x35: return GB(v->type == VEH_AIRCRAFT ? (v->cur_speed * 10) / 128 : v->cur_speed, 8, 8);
775 case 0x36: return v->subspeed;
776 case 0x37: return v->acceleration;
777 case 0x39: return v->cargo_type;
778 case 0x3A: return v->cargo_cap;
779 case 0x3B: return GB(v->cargo_cap, 8, 8);
780 case 0x3C: return ClampToU16(v->cargo.StoredCount());
781 case 0x3D: return GB(ClampToU16(v->cargo.StoredCount()), 8, 8);
782 case 0x3E: return v->cargo.Source();
783 case 0x3F: return ClampU(v->cargo.DaysInTransit(), 0, 0xFF);
784 case 0x40: return ClampToU16(v->age);
785 case 0x41: return GB(ClampToU16(v->age), 8, 8);
786 case 0x42: return ClampToU16(v->max_age);
787 case 0x43: return GB(ClampToU16(v->max_age), 8, 8);
788 case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
789 case 0x45: return v->unitnumber;
790 case 0x46: return v->GetEngine()->grf_prop.local_id;
791 case 0x47: return GB(v->GetEngine()->grf_prop.local_id, 8, 8);
792 case 0x48:
793 if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
794 return HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
796 case 0x49: return v->day_counter;
797 case 0x4A: return v->breakdowns_since_last_service;
798 case 0x4B: return v->breakdown_ctr;
799 case 0x4C: return v->breakdown_delay;
800 case 0x4D: return v->breakdown_chance;
801 case 0x4E: return v->reliability;
802 case 0x4F: return GB(v->reliability, 8, 8);
803 case 0x50: return v->reliability_spd_dec;
804 case 0x51: return GB(v->reliability_spd_dec, 8, 8);
805 case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
806 case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 8, 24);
807 case 0x54: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 16, 16);
808 case 0x55: return GB(ClampToI32(v->GetDisplayProfitThisYear()), 24, 8);
809 case 0x56: return ClampToI32(v->GetDisplayProfitLastYear());
810 case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 8, 24);
811 case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
812 case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24, 8);
813 case 0x5A: return v->Next() == NULL ? INVALID_VEHICLE : v->Next()->index;
814 case 0x5C: return ClampToI32(v->value);
815 case 0x5D: return GB(ClampToI32(v->value), 8, 24);
816 case 0x5E: return GB(ClampToI32(v->value), 16, 16);
817 case 0x5F: return GB(ClampToI32(v->value), 24, 8);
818 case 0x72: return v->cargo_subtype;
819 case 0x7A: return v->random_bits;
820 case 0x7B: return v->waiting_triggers;
823 /* Vehicle specific properties */
824 switch (v->type) {
825 case VEH_TRAIN: {
826 Train *t = Train::From(v);
827 switch (variable - 0x80) {
828 case 0x62: return t->track;
829 case 0x66: return t->railtype;
830 case 0x73: return 0x80 + VEHICLE_LENGTH - t->gcache.cached_veh_length;
831 case 0x74: return t->gcache.cached_power;
832 case 0x75: return GB(t->gcache.cached_power, 8, 24);
833 case 0x76: return GB(t->gcache.cached_power, 16, 16);
834 case 0x77: return GB(t->gcache.cached_power, 24, 8);
835 case 0x7C: return t->First()->index;
836 case 0x7D: return GB(t->First()->index, 8, 8);
837 case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
839 break;
842 case VEH_ROAD: {
843 RoadVehicle *rv = RoadVehicle::From(v);
844 switch (variable - 0x80) {
845 case 0x62: return rv->state;
846 case 0x64: return rv->blocked_ctr;
847 case 0x65: return GB(rv->blocked_ctr, 8, 8);
848 case 0x66: return rv->overtaking;
849 case 0x67: return rv->overtaking_ctr;
850 case 0x68: return rv->crashed_ctr;
851 case 0x69: return GB(rv->crashed_ctr, 8, 8);
853 break;
856 case VEH_SHIP: {
857 Ship *s = Ship::From(v);
858 switch (variable - 0x80) {
859 case 0x62: return s->state;
861 break;
864 case VEH_AIRCRAFT: {
865 Aircraft *a = Aircraft::From(v);
866 switch (variable - 0x80) {
867 case 0x62: return MapAircraftMovementState(a); // Current movement state
868 case 0x63: return a->targetairport; // Airport to which the action refers
869 case 0x66: return MapAircraftMovementAction(a); // Current movement action
871 break;
874 default: break;
877 DEBUG(grf, 1, "Unhandled vehicle variable 0x%X, type 0x%X", variable, (uint)v->type);
879 *available = false;
880 return UINT_MAX;
883 /* virtual */ uint32 VehicleScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
885 if (this->v == NULL) {
886 /* Vehicle does not exist, so we're in a purchase list */
887 switch (variable) {
888 case 0x43: return GetCompanyInfo(_current_company, LiveryHelper(this->self_type, NULL)); // Owner information
889 case 0x46: return 0; // Motion counter
890 case 0x47: { // Vehicle cargo info
891 const Engine *e = Engine::Get(this->self_type);
892 CargoID cargo_type = e->GetDefaultCargoType();
893 if (cargo_type != CT_INVALID) {
894 const CargoSpec *cs = CargoSpec::Get(cargo_type);
895 return (cs->classes << 16) | (cs->weight << 8) | this->ro.grffile->cargo_map[cargo_type];
896 } else {
897 return 0x000000FF;
900 case 0x48: return Engine::Get(this->self_type)->flags; // Vehicle Type Info
901 case 0x49: return _cur_year; // 'Long' format build year
902 case 0x4B: return _date; // Long date of last service
903 case 0x92: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF); // Date of last service
904 case 0x93: return GB(Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 0xFFFF), 8, 8);
905 case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
906 case 0xDA: return INVALID_VEHICLE; // Next vehicle
907 case 0xF2: return 0; // Cargo subtype
910 *available = false;
911 return UINT_MAX;
914 return VehicleGetVariable(const_cast<Vehicle*>(this->v), this, variable, parameter, available);
918 /* virtual */ const SpriteGroup *VehicleResolverObject::ResolveReal(const RealSpriteGroup *group) const
920 const Vehicle *v = this->self_scope.v;
922 if (v == NULL) {
923 if (group->num_loading > 0) return group->loading[0];
924 if (group->num_loaded > 0) return group->loaded[0];
925 return NULL;
928 bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
930 uint totalsets = in_motion ? group->num_loaded : group->num_loading;
932 if (totalsets == 0) return NULL;
934 uint set = (v->cargo.StoredCount() * totalsets) / max((uint16)1, v->cargo_cap);
935 set = min(set, totalsets - 1);
937 return in_motion ? group->loaded[set] : group->loading[set];
941 * Get the grf file associated with an engine type.
942 * @param engine_type Engine to query.
943 * @return grf file associated with the engine.
945 static const GRFFile *GetEngineGrfFile(EngineID engine_type)
947 const Engine *e = Engine::Get(engine_type);
948 return (e != NULL) ? e->GetGRF() : NULL;
952 * Resolver of a vehicle (chain).
953 * @param engine_type Engine type
954 * @param v %Vehicle being resolved.
955 * @param wagon_override Application of wagon overrides.
956 * @param info_view Indicates if the item is being drawn in an info window.
957 * @param callback Callback ID.
958 * @param callback_param1 First parameter (var 10) of the callback.
959 * @param callback_param2 Second parameter (var 18) of the callback.
961 VehicleResolverObject::VehicleResolverObject(EngineID engine_type, const Vehicle *v, WagonOverride wagon_override, bool info_view,
962 CallbackID callback, uint32 callback_param1, uint32 callback_param2)
963 : ResolverObject(GetEngineGrfFile(engine_type), callback, callback_param1, callback_param2),
964 self_scope(*this, engine_type, v, info_view),
965 parent_scope(*this, engine_type, ((v != NULL) ? v->First() : v), info_view),
966 relative_scope(*this, engine_type, v, info_view),
967 cached_relative_count(0)
969 if (wagon_override == WO_SELF) {
970 this->root_spritegroup = GetWagonOverrideSpriteSet(engine_type, CT_DEFAULT, engine_type);
971 } else {
972 if (wagon_override != WO_NONE && v != NULL && v->IsGroundVehicle()) {
973 assert(v->engine_type == engine_type); // overrides make little sense with fake scopes
975 /* For trains we always use cached value, except for callbacks because the override spriteset
976 * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
977 * as v->cargo_type is temporary changed to the new type */
978 if (wagon_override == WO_CACHED && v->type == VEH_TRAIN) {
979 this->root_spritegroup = Train::From(v)->tcache.cached_override;
980 } else {
981 this->root_spritegroup = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, v->GetGroundVehicleCache()->first_engine);
985 if (this->root_spritegroup == NULL) {
986 const Engine *e = Engine::Get(engine_type);
987 CargoID cargo = v != NULL ? v->cargo_type : CT_PURCHASE;
988 assert(cargo < lengthof(e->grf_prop.spritegroup));
989 this->root_spritegroup = e->grf_prop.spritegroup[cargo] != NULL ? e->grf_prop.spritegroup[cargo] : e->grf_prop.spritegroup[CT_DEFAULT];
996 void GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction, EngineImageType image_type, VehicleSpriteSeq *result)
998 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_CACHED, false, CBID_NO_CALLBACK);
999 result->Clear();
1001 bool sprite_stack = HasBit(EngInfo(engine)->misc_flags, EF_SPRITE_STACK);
1002 uint max_stack = sprite_stack ? lengthof(result->seq) : 1;
1003 for (uint stack = 0; stack < max_stack; ++stack) {
1004 object.ResetState();
1005 object.callback_param1 = image_type | (stack << 8);
1006 const SpriteGroup *group = object.Resolve();
1007 uint32 reg100 = sprite_stack ? GetRegister(0x100) : 0;
1008 if (group != NULL && group->GetNumResults() != 0) {
1009 result->seq[result->count].sprite = group->GetResult() + (direction % group->GetNumResults());
1010 result->seq[result->count].pal = GB(reg100, 0, 16); // zero means default recolouring
1011 result->count++;
1013 if (!HasBit(reg100, 31)) break;
1018 void GetRotorOverrideSprite(EngineID engine, const struct Aircraft *v, bool info_view, EngineImageType image_type, VehicleSpriteSeq *result)
1020 const Engine *e = Engine::Get(engine);
1022 /* Only valid for helicopters */
1023 assert(e->type == VEH_AIRCRAFT);
1024 assert(!(e->u.air.subtype & AIR_CTOL));
1026 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_SELF, info_view, CBID_NO_CALLBACK);
1027 result->Clear();
1028 uint rotor_pos = v == NULL || info_view ? 0 : v->Next()->Next()->state;
1030 bool sprite_stack = HasBit(e->info.misc_flags, EF_SPRITE_STACK);
1031 uint max_stack = sprite_stack ? lengthof(result->seq) : 1;
1032 for (uint stack = 0; stack < max_stack; ++stack) {
1033 object.ResetState();
1034 object.callback_param1 = image_type | (stack << 8);
1035 const SpriteGroup *group = object.Resolve();
1036 uint32 reg100 = sprite_stack ? GetRegister(0x100) : 0;
1037 if (group != NULL && group->GetNumResults() != 0) {
1038 result->seq[result->count].sprite = group->GetResult() + (rotor_pos % group->GetNumResults());
1039 result->seq[result->count].pal = GB(reg100, 0, 16); // zero means default recolouring
1040 result->count++;
1042 if (!HasBit(reg100, 31)) break;
1048 * Check if a wagon is currently using a wagon override
1049 * @param v The wagon to check
1050 * @return true if it is using an override, false otherwise
1052 bool UsesWagonOverride(const Vehicle *v)
1054 assert(v->type == VEH_TRAIN);
1055 return Train::From(v)->tcache.cached_override != NULL;
1059 * Evaluate a newgrf callback for vehicles
1060 * @param callback The callback to evaluate
1061 * @param param1 First parameter of the callback
1062 * @param param2 Second parameter of the callback
1063 * @param engine Engine type of the vehicle to evaluate the callback for
1064 * @param v The vehicle to evaluate the callback for, or NULL if it doesnt exist yet
1065 * @return The value the callback returned, or CALLBACK_FAILED if it failed
1067 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
1069 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_UNCACHED, false, callback, param1, param2);
1070 return object.ResolveCallback();
1074 * Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
1075 * @param callback The callback to evaluate
1076 * @param param1 First parameter of the callback
1077 * @param param2 Second parameter of the callback
1078 * @param engine Engine type of the vehicle to evaluate the callback for
1079 * @param v The vehicle to evaluate the callback for, or NULL if it doesn't exist yet
1080 * @param parent The vehicle to use for parent scope
1081 * @return The value the callback returned, or CALLBACK_FAILED if it failed
1083 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
1085 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_NONE, false, callback, param1, param2);
1086 object.parent_scope.SetVehicle(parent);
1087 return object.ResolveCallback();
1091 /* Callback 36 handlers */
1092 uint GetVehicleProperty(const Vehicle *v, PropertyID property, uint orig_value)
1094 return GetEngineProperty(v->engine_type, property, orig_value, v);
1098 uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value, const Vehicle *v)
1100 uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, engine, v);
1101 if (callback != CALLBACK_FAILED) return callback;
1103 return orig_value;
1107 static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
1109 /* We can't trigger a non-existent vehicle... */
1110 assert(v != NULL);
1112 VehicleResolverObject object(v->engine_type, v, VehicleResolverObject::WO_CACHED, false, CBID_RANDOM_TRIGGER);
1113 object.waiting_triggers = v->waiting_triggers | trigger;
1114 v->waiting_triggers = object.waiting_triggers; // store now for var 5F
1116 const SpriteGroup *group = object.Resolve();
1117 if (group == NULL) return;
1119 /* Store remaining triggers. */
1120 v->waiting_triggers = object.GetRemainingTriggers();
1122 /* Rerandomise bits. Scopes other than SELF are invalid for rerandomisation. For bug-to-bug-compatibility with TTDP we ignore the scope. */
1123 byte new_random_bits = Random();
1124 uint32 reseed = object.GetReseedSum();
1125 v->random_bits &= ~reseed;
1126 v->random_bits |= (first ? new_random_bits : base_random_bits) & reseed;
1128 switch (trigger) {
1129 case VEHICLE_TRIGGER_NEW_CARGO:
1130 /* All vehicles in chain get ANY_NEW_CARGO trigger now.
1131 * So we call it for the first one and they will recurse.
1132 * Indexing part of vehicle random bits needs to be
1133 * same for all triggered vehicles in the chain (to get
1134 * all the random-cargo wagons carry the same cargo,
1135 * i.e.), so we give them all the NEW_CARGO triggered
1136 * vehicle's portion of random bits. */
1137 assert(first);
1138 DoTriggerVehicle(v->First(), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
1139 break;
1141 case VEHICLE_TRIGGER_DEPOT:
1142 /* We now trigger the next vehicle in chain recursively.
1143 * The random bits portions may be different for each
1144 * vehicle in chain. */
1145 if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, 0, true);
1146 break;
1148 case VEHICLE_TRIGGER_EMPTY:
1149 /* We now trigger the next vehicle in chain
1150 * recursively. The random bits portions must be same
1151 * for each vehicle in chain, so we give them all
1152 * first chained vehicle's portion of random bits. */
1153 if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
1154 break;
1156 case VEHICLE_TRIGGER_ANY_NEW_CARGO:
1157 /* Now pass the trigger recursively to the next vehicle
1158 * in chain. */
1159 assert(!first);
1160 if (v->Next() != NULL) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
1161 break;
1163 case VEHICLE_TRIGGER_CALLBACK_32:
1164 /* Do not do any recursion */
1165 break;
1169 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
1171 if (trigger == VEHICLE_TRIGGER_DEPOT) {
1172 /* store that the vehicle entered a depot this tick */
1173 VehicleEnteredDepotThisTick(v);
1176 v->InvalidateNewGRFCacheOfChain();
1177 DoTriggerVehicle(v, trigger, 0, true);
1178 v->InvalidateNewGRFCacheOfChain();
1181 /* Functions for changing the order of vehicle purchase lists */
1183 struct ListOrderChange {
1184 EngineID engine;
1185 uint target; ///< local ID
1188 static SmallVector<ListOrderChange, 16> _list_order_changes;
1191 * Record a vehicle ListOrderChange.
1192 * @param engine Engine to move
1193 * @param target Local engine ID to move \a engine in front of
1194 * @note All sorting is done later in CommitVehicleListOrderChanges
1196 void AlterVehicleListOrder(EngineID engine, uint target)
1198 /* Add the list order change to a queue */
1199 ListOrderChange *loc = _list_order_changes.Append();
1200 loc->engine = engine;
1201 loc->target = target;
1205 * Comparator function to sort engines via scope-GRFID and local ID.
1206 * @param a left side
1207 * @param b right side
1208 * @return comparison result
1210 static int CDECL EnginePreSort(const EngineID *a, const EngineID *b)
1212 const EngineIDMapping *id_a = _engine_mngr.Get(*a);
1213 const EngineIDMapping *id_b = _engine_mngr.Get(*b);
1215 /* 1. Sort by engine type */
1216 if (id_a->type != id_b->type) return (int)id_a->type - (int)id_b->type;
1218 /* 2. Sort by scope-GRFID */
1219 if (id_a->grfid != id_b->grfid) return id_a->grfid < id_b->grfid ? -1 : 1;
1221 /* 3. Sort by local ID */
1222 return (int)id_a->internal_id - (int)id_b->internal_id;
1226 * Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
1228 void CommitVehicleListOrderChanges()
1230 /* Pre-sort engines by scope-grfid and local index */
1231 SmallVector<EngineID, 16> ordering;
1232 Engine *e;
1233 FOR_ALL_ENGINES(e) {
1234 *ordering.Append() = e->index;
1236 QSortT(ordering.Begin(), ordering.Length(), EnginePreSort);
1238 /* Apply Insertion-Sort operations */
1239 const ListOrderChange *end = _list_order_changes.End();
1240 for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) {
1241 EngineID source = it->engine;
1242 uint local_target = it->target;
1244 const EngineIDMapping *id_source = _engine_mngr.Get(source);
1245 if (id_source->internal_id == local_target) continue;
1247 EngineID target = _engine_mngr.GetID(id_source->type, local_target, id_source->grfid);
1248 if (target == INVALID_ENGINE) continue;
1250 int source_index = ordering.FindIndex(source);
1251 int target_index = ordering.FindIndex(target);
1253 assert(source_index >= 0 && target_index >= 0);
1254 assert(source_index != target_index);
1256 EngineID *list = ordering.Begin();
1257 if (source_index < target_index) {
1258 --target_index;
1259 for (int i = source_index; i < target_index; ++i) list[i] = list[i + 1];
1260 list[target_index] = source;
1261 } else {
1262 for (int i = source_index; i > target_index; --i) list[i] = list[i - 1];
1263 list[target_index] = source;
1267 /* Store final sort-order */
1268 const EngineID *idend = ordering.End();
1269 uint index = 0;
1270 for (const EngineID *it = ordering.Begin(); it != idend; ++it, ++index) {
1271 Engine::Get(*it)->list_position = index;
1274 /* Clear out the queue */
1275 _list_order_changes.Reset();
1279 * Fill the grf_cache of the given vehicle.
1280 * @param v The vehicle to fill the cache for.
1282 void FillNewGRFVehicleCache(const Vehicle *v)
1284 VehicleResolverObject ro(v->engine_type, v, VehicleResolverObject::WO_NONE);
1286 /* These variables we have to check; these are the ones with a cache. */
1287 static const int cache_entries[][2] = {
1288 { 0x40, NCVV_POSITION_CONSIST_LENGTH },
1289 { 0x41, NCVV_POSITION_SAME_ID_LENGTH },
1290 { 0x42, NCVV_CONSIST_CARGO_INFORMATION },
1291 { 0x43, NCVV_COMPANY_INFORMATION },
1292 { 0x4D, NCVV_POSITION_IN_VEHICLE },
1294 assert_compile(NCVV_END == lengthof(cache_entries));
1296 /* Resolve all the variables, so their caches are set. */
1297 for (size_t i = 0; i < lengthof(cache_entries); i++) {
1298 /* Only resolve when the cache isn't valid. */
1299 if (HasBit(v->grf_cache.cache_valid, cache_entries[i][1])) continue;
1300 bool stub;
1301 ro.GetScope(VSG_SCOPE_SELF)->GetVariable(cache_entries[i][0], 0, &stub);
1304 /* Make sure really all bits are set. */
1305 assert(v->grf_cache.cache_valid == (1 << NCVV_END) - 1);