OpenTTD

newgrf_engine.cpp
Go to the documentation of this file.
1 /* $Id: newgrf_engine.cpp 27984 2018-03-11 13:19:41Z frosch $ */
2
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 */
9
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"
27
28 #include "safeguards.h"
29
30 struct WagonOverride {
31 EngineID *train_id;
32 uint trains;
33 CargoID cargo;
34 const SpriteGroup *group;
35 };
36
37 void SetWagonOverrideSprites(EngineID engine, CargoID cargo, const SpriteGroup *group, EngineID *train_id, uint trains)
38 {
39 Engine *e = Engine::Get(engine);
40 WagonOverride *wo;
41
42 assert(cargo < NUM_CARGO + 2); // Include CT_DEFAULT and CT_PURCHASE pseudo cargoes.
43
44 e->overrides_count++;
45 e->overrides = ReallocT(e->overrides, e->overrides_count);
46
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);
53 }
54
55 const SpriteGroup *GetWagonOverrideSpriteSet(EngineID engine, CargoID cargo, EngineID overriding_engine)
56 {
57 const Engine *e = Engine::Get(engine);
58
59 for (uint i = 0; i < e->overrides_count; i++) {
60 const WagonOverride *wo = &e->overrides[i];
61
62 if (wo->cargo != cargo && wo->cargo != CT_DEFAULT) continue;
63
64 for (uint j = 0; j < wo->trains; j++) {
65 if (wo->train_id[j] == overriding_engine) return wo->group;
66 }
67 }
68 return NULL;
69 }
70
74 void UnloadWagonOverrides(Engine *e)
75 {
76 for (uint i = 0; i < e->overrides_count; i++) {
77 WagonOverride *wo = &e->overrides[i];
78 free(wo->train_id);
79 }
80 free(e->overrides);
81 e->overrides_count = 0;
82 e->overrides = NULL;
83 }
84
85
86 void SetCustomEngineSprites(EngineID engine, byte cargo, const SpriteGroup *group)
87 {
88 Engine *e = Engine::Get(engine);
89 assert(cargo < lengthof(e->grf_prop.spritegroup));
90
91 if (e->grf_prop.spritegroup[cargo] != NULL) {
92 grfmsg(6, "SetCustomEngineSprites: engine %d cargo %d already has group -- replacing", engine, cargo);
93 }
94 e->grf_prop.spritegroup[cargo] = group;
95 }
96
97
104 void SetEngineGRF(EngineID engine, const GRFFile *file)
105 {
106 Engine *e = Engine::Get(engine);
107 e->grf_prop.grffile = file;
108 }
109
110
111 static int MapOldSubType(const Vehicle *v)
112 {
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();
124 }
125 }
126
127
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,
159 };
160
161
166 static byte MapAircraftMovementState(const Aircraft *v)
167 {
168 const Station *st = GetTargetAirportIfValid(v);
169 if (st == NULL) return AMS_TTDP_FLIGHT_TO_TOWER;
170
171 const AirportFTAClass *afc = st->airport.GetFTA();
172 uint16 amdflag = afc->MovingData(v->pos)->flag;
173
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. */
179
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;
183
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;
187
188 /* The final two conditions apply to helicopters or aircraft.
189 * Has reached hangar? */
190 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_HANGAR;
191
192 /* Still moving towards hangar. */
193 return AMS_TTDP_TO_HANGAR;
194
195 case TERM1:
196 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD1;
197 return AMS_TTDP_TO_JUNCTION;
198
199 case TERM2:
200 if (amdflag & AMED_EXACTPOS) return AMS_TTDP_TO_PAD2;
201 return AMS_TTDP_TO_ENTRY_2_AND_3_AND_H;
202
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;
212
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.
220
221 case TAKEOFF: // Moving to takeoff position.
222 return AMS_TTDP_TO_OUTWAY;
223
224 case STARTTAKEOFF: // Accelerating down runway.
225 return AMS_TTDP_TAKEOFF;
226
227 case ENDTAKEOFF: // Ascent
228 return AMS_TTDP_CLIMBING;
229
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;
236 }
237
238 case FLYING:
239 return amdflag & AMED_HOLD ? AMS_TTDP_FLIGHT_APPROACH : AMS_TTDP_FLIGHT_TO_TOWER;
240
241 case LANDING: // Descent
242 return AMS_TTDP_FLIGHT_DESCENT;
243
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;
248
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;
256 }
257
258 default:
259 return AMS_TTDP_HANGAR;
260 }
261 }
262
263
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,
285 };
286
287
293 static byte MapAircraftMovementAction(const Aircraft *v)
294 {
295 switch (v->state) {
296 case HANGAR:
297 return (v->cur_speed > 0) ? AMA_TTDP_LANDING_TO_HANGAR : AMA_TTDP_IN_HANGAR;
298
299 case TERM1:
300 case HELIPAD1:
301 return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD1 : AMA_TTDP_LANDING_TO_PAD1;
302
303 case TERM2:
304 case HELIPAD2:
305 return (v->current_order.IsType(OT_LOADING)) ? AMA_TTDP_ON_PAD2 : AMA_TTDP_LANDING_TO_PAD2;
306
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;
315
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;
322
323 case FLYING:
324 return AMA_TTDP_IN_FLIGHT;
325
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;
333
334 default:
335 return AMA_TTDP_IN_HANGAR;
336 }
337 }
338
339
340 /* virtual */ uint32 VehicleScopeResolver::GetRandomBits() const
341 {
342 return this->v == NULL ? 0 : this->v->random_bits;
343 }
344
345 /* virtual */ uint32 VehicleScopeResolver::GetTriggers() const
346 {
347 return this->v == NULL ? 0 : this->v->waiting_triggers;
348 }
349
350
351 /* virtual */ ScopeResolver *VehicleResolverObject::GetScope(VarSpriteGroupScope scope, byte relative)
352 {
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);
362
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;
383 }
384 }
385 if (v == NULL) v = self;
386 break;
387 }
388 }
389 this->relative_scope.SetVehicle(v->Move(count));
390 }
391 return &this->relative_scope;
392 }
393 default: return ResolverObject::GetScope(scope, relative);
394 }
395 }
396
406 static const Livery *LiveryHelper(EngineID engine, const Vehicle *v)
407 {
408 const Livery *l;
409
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);
417 }
418
419 return l;
420 }
421
429 static uint32 PositionHelper(const Vehicle *v, bool consecutive)
430 {
431 const Vehicle *u;
432 byte chain_before = 0;
433 byte chain_after = 0;
434
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;
438 }
439
440 while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
441 chain_after++;
442 u = u->Next();
443 }
444
445 return chain_before | chain_after << 8 | (chain_before + chain_after + consecutive) << 16;
446 }
447
448 static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object, byte variable, uint32 parameter, bool *available)
449 {
450 /* Calculated vehicle parameters */
451 switch (variable) {
452 case 0x25: // Get engine GRF ID
453 return v->GetGRFID();
454
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);
459 }
460 return v->grf_cache.position_consist_length;
461
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);
466 }
467 return v->grf_cache.position_same_id_length;
468
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
478
479 /* Reset our arrays */
480 memset(common_cargoes, 0, sizeof(common_cargoes));
481 memset(common_subtypes, 0, sizeof(common_subtypes));
482
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;
485
486 /* Skip empty engines */
487 if (!u->GetEngine()->CanCarryCargo()) continue;
488
489 cargo_classes |= CargoSpec::Get(u->cargo_type)->classes;
490 common_cargoes[u->cargo_type]++;
491 }
492
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;
499 }
500 }
501
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;
506
507 common_subtypes[u->cargo_subtype]++;
508 }
509
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;
516 }
517 }
518
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);
523 }
524
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;
527
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().
535 */
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];
539
540 return (v->grf_cache.consist_cargo_information & 0xFFFF00FF) | common_bitnum << 8;
541 }
542
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);
547 }
548 return v->grf_cache.company_information;
549
550 case 0x44: // Aircraft information
551 if (v->type != VEH_AIRCRAFT || !Aircraft::From(v)->IsNormalAircraft()) return UINT_MAX;
552
553 {
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;
557
558 const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
559
560 if (st != NULL && st->airport.tile != INVALID_TILE) {
561 airporttype = st->airport.GetSpec()->ttd_airport_type;
562 }
563
564 return (Clamp(altitude, 0, 0xFF) << 8) | airporttype;
565 }
566
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
572 */
573 if (!v->IsGroundVehicle()) return 0;
574
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);
580
581 return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
582 ((b > DIRDIFF_REVERSE ? b | 8 : b) << 8) |
583 ( f > DIRDIFF_REVERSE ? f | 8 : f);
584 }
585
586 case 0x46: // Motion counter
587 return v->motion_counter;
588
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.
595 */
596 const CargoSpec *cs = CargoSpec::Get(v->cargo_type);
597
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().
602 */
603 return (cs->classes << 16) | (cs->weight << 8) | object->ro.grffile->cargo_map[v->cargo_type];
604 }
605
606 case 0x48: return v->GetEngine()->flags; // Vehicle Type Info
607 case 0x49: return v->build_year;
608
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);
613 }
614
615 case 0x4B: // Long date of last service
616 return v->date_of_last_service;
617
618 case 0x4C: // Current maximum speed in NewGRF units
619 if (!v->IsPrimaryVehicle()) return 0;
620 return v->GetCurrentMaxSpeed();
621
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);
630 }
631 return v->grf_cache.position_in_vehicle;
632
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;
636
637 {
638 uint count = 0;
639 for (; v != NULL; v = v->Next()) {
640 if (v->GetEngine()->grf_prop.local_id == parameter) count++;
641 }
642 return count;
643 }
644
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;
649 }
650
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
657
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);
663 }
664 }
665 /* Not available */
666 break;
667
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.
675 */
676 if (!v->IsGroundVehicle()) return 0;
677
678 const Vehicle *u = v->Move((int8)parameter);
679 if (u == NULL) return 0;
680
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;
685
686 if (u->vehstatus & VS_HIDDEN) ret |= 0x80;
687
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;
692
693 return ret;
694 }
695
696 case 0xFE:
697 case 0xFF: {
698 uint16 modflags = 0;
699
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);
707
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);
711 }
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);
714
715 return variable == 0xFE ? modflags : GB(modflags, 8, 8);
716 }
717 }
718
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;
739 }
740 }
741 return (variable - 0x80) == 0x10 ? ticks : GB(ticks, 8, 8);
742 }
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;
756
757 default:
758 max_speed = v->vcache.cached_max_speed;
759 break;
760 }
761 return (variable - 0x80) == 0x18 ? max_speed : GB(max_speed, 8, 8);
762 }
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;
795
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;
821 }
822
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
838 }
839 break;
840 }
841
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);
852 }
853 break;
854 }
855
856 case VEH_SHIP: {
857 Ship *s = Ship::From(v);
858 switch (variable - 0x80) {
859 case 0x62: return s->state;
860 }
861 break;
862 }
863
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
870 }
871 break;
872 }
873
874 default: break;
875 }
876
877 DEBUG(grf, 1, "Unhandled vehicle variable 0x%X, type 0x%X", variable, (uint)v->type);
878
879 *available = false;
880 return UINT_MAX;
881 }
882
883 /* virtual */ uint32 VehicleScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
884 {
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;
898 }
899 }
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
908 }
909
910 *available = false;
911 return UINT_MAX;
912 }
913
914 return VehicleGetVariable(const_cast<Vehicle*>(this->v), this, variable, parameter, available);
915 }
916
917
918 /* virtual */ const SpriteGroup *VehicleResolverObject::ResolveReal(const RealSpriteGroup *group) const
919 {
920 const Vehicle *v = this->self_scope.v;
921
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;
926 }
927
928 bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
929
930 uint totalsets = in_motion ? group->num_loaded : group->num_loading;
931
932 if (totalsets == 0) return NULL;
933
934 uint set = (v->cargo.StoredCount() * totalsets) / max((uint16)1, v->cargo_cap);
935 set = min(set, totalsets - 1);
936
937 return in_motion ? group->loaded[set] : group->loading[set];
938 }
939
945 static const GRFFile *GetEngineGrfFile(EngineID engine_type)
946 {
947 const Engine *e = Engine::Get(engine_type);
948 return (e != NULL) ? e->GetGRF() : NULL;
949 }
950
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)
968 {
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
974
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);
982 }
983 }
984
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];
990 }
991 }
992 }
993
994
995
996 void GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction, EngineImageType image_type, VehicleSpriteSeq *result)
997 {
998 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_CACHED, false, CBID_NO_CALLBACK);
999 result->Clear();
1000
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++;
1012 }
1013 if (!HasBit(reg100, 31)) break;
1014 }
1015 }
1016
1017
1018 void GetRotorOverrideSprite(EngineID engine, const struct Aircraft *v, bool info_view, EngineImageType image_type, VehicleSpriteSeq *result)
1019 {
1020 const Engine *e = Engine::Get(engine);
1021
1022 /* Only valid for helicopters */
1023 assert(e->type == VEH_AIRCRAFT);
1024 assert(!(e->u.air.subtype & AIR_CTOL));
1025
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;
1029
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++;
1041 }
1042 if (!HasBit(reg100, 31)) break;
1043 }
1044 }
1045
1046
1052 bool UsesWagonOverride(const Vehicle *v)
1053 {
1054 assert(v->type == VEH_TRAIN);
1055 return Train::From(v)->tcache.cached_override != NULL;
1056 }
1057
1067 uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
1068 {
1069 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_UNCACHED, false, callback, param1, param2);
1070 return object.ResolveCallback();
1071 }
1072
1083 uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
1084 {
1085 VehicleResolverObject object(engine, v, VehicleResolverObject::WO_NONE, false, callback, param1, param2);
1086 object.parent_scope.SetVehicle(parent);
1087 return object.ResolveCallback();
1088 }
1089
1090
1091 /* Callback 36 handlers */
1092 uint GetVehicleProperty(const Vehicle *v, PropertyID property, uint orig_value)
1093 {
1094 return GetEngineProperty(v->engine_type, property, orig_value, v);
1095 }
1096
1097
1098 uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value, const Vehicle *v)
1099 {
1100 uint16 callback = GetVehicleCallback(CBID_VEHICLE_MODIFY_PROPERTY, property, 0, engine, v);
1101 if (callback != CALLBACK_FAILED) return callback;
1102
1103 return orig_value;
1104 }
1105
1106
1107 static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
1108 {
1109 /* We can't trigger a non-existent vehicle... */
1110 assert(v != NULL);
1111
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
1115
1116 const SpriteGroup *group = object.Resolve();
1117 if (group == NULL) return;
1118
1119 /* Store remaining triggers. */
1120 v->waiting_triggers = object.GetRemainingTriggers();
1121
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;
1127
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;
1140
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;
1147
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;
1155
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;
1162
1163 case VEHICLE_TRIGGER_CALLBACK_32:
1164 /* Do not do any recursion */
1165 break;
1166 }
1167 }
1168
1169 void TriggerVehicle(Vehicle *v, VehicleTrigger trigger)
1170 {
1171 if (trigger == VEHICLE_TRIGGER_DEPOT) {
1172 /* store that the vehicle entered a depot this tick */
1173 VehicleEnteredDepotThisTick(v);
1174 }
1175
1176 v->InvalidateNewGRFCacheOfChain();
1177 DoTriggerVehicle(v, trigger, 0, true);
1178 v->InvalidateNewGRFCacheOfChain();
1179 }
1180
1181 /* Functions for changing the order of vehicle purchase lists */
1182
1183 struct ListOrderChange {
1184 EngineID engine;
1185 uint target;
1186 };
1187
1188 static SmallVector<ListOrderChange, 16> _list_order_changes;
1189
1196 void AlterVehicleListOrder(EngineID engine, uint target)
1197 {
1198 /* Add the list order change to a queue */
1199 ListOrderChange *loc = _list_order_changes.Append();
1200 loc->engine = engine;
1201 loc->target = target;
1202 }
1203
1210 static int CDECL EnginePreSort(const EngineID *a, const EngineID *b)
1211 {
1212 const EngineIDMapping *id_a = _engine_mngr.Get(*a);
1213 const EngineIDMapping *id_b = _engine_mngr.Get(*b);
1214
1215 /* 1. Sort by engine type */
1216 if (id_a->type != id_b->type) return (int)id_a->type - (int)id_b->type;
1217
1218 /* 2. Sort by scope-GRFID */
1219 if (id_a->grfid != id_b->grfid) return id_a->grfid < id_b->grfid ? -1 : 1;
1220
1221 /* 3. Sort by local ID */
1222 return (int)id_a->internal_id - (int)id_b->internal_id;
1223 }
1224
1228 void CommitVehicleListOrderChanges()
1229 {
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;
1235 }
1236 QSortT(ordering.Begin(), ordering.Length(), EnginePreSort);
1237
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;
1243
1244 const EngineIDMapping *id_source = _engine_mngr.Get(source);
1245 if (id_source->internal_id == local_target) continue;
1246
1247 EngineID target = _engine_mngr.GetID(id_source->type, local_target, id_source->grfid);
1248 if (target == INVALID_ENGINE) continue;
1249
1250 int source_index = ordering.FindIndex(source);
1251 int target_index = ordering.FindIndex(target);
1252
1253 assert(source_index >= 0 && target_index >= 0);
1254 assert(source_index != target_index);
1255
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;
1264 }
1265 }
1266
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;
1272 }
1273
1274 /* Clear out the queue */
1275 _list_order_changes.Reset();
1276 }
1277
1282 void FillNewGRFVehicleCache(const Vehicle *v)
1283 {
1284 VehicleResolverObject ro(v->engine_type, v, VehicleResolverObject::WO_NONE);
1285
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 },
1293 };
1294 assert_compile(NCVV_END == lengthof(cache_entries));
1295
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);
1302 }
1303
1304 /* Make sure really all bits are set. */
1305 assert(v->grf_cache.cache_valid == (1 << NCVV_END) - 1);
1306 }
VehicleCargoList::Source
StationID Source() const
Returns source of the first cargo packet in this list.
Definition: cargopacket.h:337
WagonOverride
Definition: newgrf_engine.cpp:30
roadveh.h
Road vehicle states.
HasPowerOnRail
static bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition: rail.h:324
AirportSpec::ttd_airport_type
TTDPAirportType ttd_airport_type
ttdpatch airport type (Small/Large/Helipad/Oilrig)
Definition: newgrf_airport.h:114
ScopeResolver
Interface to query and set values specific to a single VarSpriteGroupScope (action 2 scope)...
Definition: newgrf_spritegroup.h:291
Vehicle::max_age
Date max_age
Maximum age.
Definition: vehicle_base.h:259
NCVV_POSITION_SAME_ID_LENGTH
This bit will be set if the NewGRF var 41 currently stored is valid.
Definition: vehicle_base.h:59
Vehicle::Previous
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Definition: vehicle_base.h:589
TAKEOFF
Airplane wants to leave the airport.
Definition: airport.h:73
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:309
RoadVehicle::state
byte state
Definition: roadveh.h:89
VehicleScopeResolver
Resolver for a vehicle scope.
Definition: newgrf_engine.h:24
HANGAR
Heading for hangar.
Definition: airport.h:64
company_base.h
Definition of stuff that is very close to a company, like the company struct itself.
Vehicle::motion_counter
uint32 motion_counter
counter to occasionally play a vehicle sound.
Definition: vehicle_base.h:296
TERM1
Heading for terminal 1.
Definition: airport.h:65
Vehicle::value
Money value
Value of the vehicle.
Definition: vehicle_base.h:241
ENDTAKEOFF
Airplane has reached end-point of the take-off runway.
Definition: airport.h:75
newgrf_railtype.h
NewGRF handling of rail types.
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:406
AirportFTAClass
Finite sTate mAchine (FTA) of an airport.
Definition: airport.h:144
HELIPAD2
Heading for helipad 2.
Definition: airport.h:72
NCVV_POSITION_CONSIST_LENGTH
This bit will be set if the NewGRF var 40 currently stored is valid.
Definition: vehicle_base.h:58
Airport::GetSpec
const AirportSpec * GetSpec() const
Get the AirportSpec that from the airport type of this airport.
Definition: station_base.h:320
CargoSpec::weight
uint8 weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:61
UsesWagonOverride
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
Definition: newgrf_engine.cpp:1052
Aircraft::targetairport
StationID targetairport
Airport to go to next.
Definition: aircraft.h:78
AlterVehicleListOrder
void AlterVehicleListOrder(EngineID engine, uint target)
Record a vehicle ListOrderChange.
Definition: newgrf_engine.cpp:1196
UnloadWagonOverrides
void UnloadWagonOverrides(Engine *e)
Unload all wagon override sprite groups.
Definition: newgrf_engine.cpp:74
Vehicle::GetDisplayProfitThisYear
Money GetDisplayProfitThisYear() const
Gets the profit vehicle had this year.
Definition: vehicle_base.h:567
Vehicle::direction
DirectionByte direction
facing
Definition: vehicle_base.h:271
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:29
ListOrderChange::target
uint target
local ID
Definition: newgrf_engine.cpp:1185
EngineIDMapping::grfid
uint32 grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:149
ScopeResolver::ro
ResolverObject & ro
Surrounding resolver object.
Definition: newgrf_spritegroup.h:292
DAYS_TILL_ORIGINAL_BASE_YEAR
#define DAYS_TILL_ORIGINAL_BASE_YEAR
The offset in days from the &#39;_date == 0&#39; till &#39;ConvertYMDToDate(ORIGINAL_BASE_YEAR, 0, 1)&#39;.
Definition: date_type.h:82
VarSpriteGroupScope
VarSpriteGroupScope
Definition: newgrf_spritegroup.h:100
GetEngineGrfFile
static const GRFFile * GetEngineGrfFile(EngineID engine_type)
Get the grf file associated with an engine type.
Definition: newgrf_engine.cpp:945
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:246
Engine::CanCarryCargo
bool CanCarryCargo() const
Determines whether an engine can carry something.
Definition: engine.cpp:173
date_func.h
Functions related to dates.
AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
Definition: engine_type.h:93
TERM6
Heading for terminal 6.
Definition: airport.h:70
ORIGINAL_MAX_YEAR
static const Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: date_type.h:55
SmallVector::Reset
void Reset()
Remove all items from the list and free allocated memory.
Definition: smallvec_type.hpp:109
Airport::GetFTA
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
Definition: station_base.h:332
Vehicle::breakdown_delay
byte breakdown_delay
Counter for managing breakdown length.
Definition: vehicle_base.h:264
AMED_HELI_LOWER
Helicopter landing.
Definition: airport.h:57
train.h
Base for the train class.
GetVehicleCallbackParent
uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
Definition: newgrf_engine.cpp:1083
EngineIDMapping
Definition: engine_base.h:148
debug.h
Functions related to debugging.
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:123
CBID_VEHICLE_SPAWN_VISUAL_EFFECT
Called to spawn visual effects for vehicles.
Definition: newgrf_callbacks.h:283
Aircraft::pos
byte pos
Next desired position of the aircraft.
Definition: aircraft.h:76
Vehicle::cur_speed
uint16 cur_speed
current speed
Definition: vehicle_base.h:293
AMED_BRAKE
Taxiing at the airport.
Definition: airport.h:55
ResolverObject
Interface for SpriteGroup-s to access the gamestate.
Definition: newgrf_spritegroup.h:310
Engine::grf_prop
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:60
VEH_DISASTER
Disaster vehicle type.
Definition: vehicle_type.h:32
MapAircraftMovementState
static byte MapAircraftMovementState(const Aircraft *v)
Map OTTD aircraft movement states to TTDPatch style movement states (VarAction 2 Variable 0xE2) ...
Definition: newgrf_engine.cpp:166
Vehicle::spritenum
byte spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
Definition: vehicle_base.h:279
DIRDIFF_SAME
Both directions faces to the same direction.
Definition: direction_type.h:66
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:56
LiveryHelper
static const Livery * LiveryHelper(EngineID engine, const Vehicle *v)
Determines the livery of an engine.
Definition: newgrf_engine.cpp:406
Train::wait_counter
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition: train.h:103
vehicle_func.h
Functions related to vehicles.
Aircraft
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition: aircraft.h:74
NCVV_COMPANY_INFORMATION
This bit will be set if the NewGRF var 43 currently stored is valid.
Definition: vehicle_base.h:61
CBID_VEHICLE_START_STOP_CHECK
Called when the company (or AI) tries to start or stop a vehicle.
Definition: newgrf_callbacks.h:143
GetEngineLivery
const Livery * GetEngineLivery(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v, byte livery_setting)
Determines the livery for a vehicle.
Definition: vehicle.cpp:1876
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:212
VehicleSpriteSeq::Clear
void Clear()
Clear all information.
Definition: vehicle_base.h:155
CargoList::DaysInTransit
uint DaysInTransit() const
Returns average number of days in transit for a cargo entity.
Definition: cargopacket.h:270
SmallVector::Begin
const T * Begin() const
Get the pointer to the first item (const)
Definition: smallvec_type.hpp:272
CBID_NO_CALLBACK
Set when using the callback resolve system, but not to resolve a callback.
Definition: newgrf_callbacks.h:24
Ship::state
TrackBitsByte state
The "track" the ship is following.
Definition: ship.h:25
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:147
FLYING
Vehicle is flying in the air.
Definition: airport.h:77
EngineOverrideManager::GetID
EngineID GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition: engine.cpp:511
CommitVehicleListOrderChanges
void CommitVehicleListOrderChanges()
Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
Definition: newgrf_engine.cpp:1228
ListOrderChange
Definition: newgrf_engine.cpp:1183
SpecializedVehicle::First
T * First() const
Get the first vehicle in the chain.
Definition: vehicle_base.h:1010
VF_CARGO_UNLOADING
Vehicle is unloading cargo.
Definition: vehicle_base.h:45
aircraft.h
Base for aircraft.
PropertyID
PropertyID
List of NewGRF properties used in Action 0 or Callback 0x36 (CBID_VEHICLE_MODIFY_PROPERTY).
Definition: newgrf_properties.h:20
ResolverObject::GetScope
virtual ScopeResolver * GetScope(VarSpriteGroupScope scope=VSG_SCOPE_SELF, byte relative=0)
Get a resolver for the scope.
Definition: newgrf_spritegroup.cpp:142
Vehicle::last_station_visited
StationID last_station_visited
The last station we stopped at.
Definition: vehicle_base.h:302
Vehicle::reliability_spd_dec
uint16 reliability_spd_dec
Reliability decrease speed.
Definition: vehicle_base.h:262
NewGRFCache::position_consist_length
uint32 position_consist_length
Cache for NewGRF var 40.
Definition: vehicle_base.h:69
SmallVector
Simple vector template class.
Definition: smallvec_type.hpp:29
TrainCache::user_def_data
byte user_def_data
Cached property 0x25. Can be set by Callback 0x36.
Definition: train.h:79
CBID_TRAIN_ALLOW_WAGON_ATTACH
Determine whether a wagon can be attached to an already existing train.
Definition: newgrf_callbacks.h:74
VSG_SCOPE_RELATIVE
Relative position (vehicles only)
Definition: newgrf_spritegroup.h:105
RealSpriteGroup::num_loaded
byte num_loaded
Number of loaded groups.
Definition: newgrf_spritegroup.h:90
GroundVehicleCache::cached_power
uint32 cached_power
Total power of the consist (valid only for the first engine).
Definition: ground_vehicle.hpp:40
ResolverObject::reseed
uint32 reseed[VSG_END]
Collects bits to rerandomise while triggering triggers.
Definition: newgrf_spritegroup.h:336
INVALID_VEHICLE
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
Definition: vehicle_type.h:57
max
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:26
Order::MapOldOrder
uint16 MapOldOrder() const
Pack this order into a 16 bits integer as close to the TTD representation as possible.
Definition: order_cmd.cpp:209
CargoSpec::classes
uint16 classes
Classes of this cargo type.
Definition: cargotype.h:79
Vehicle::vehstatus
byte vehstatus
Status.
Definition: vehicle_base.h:317
EngineImageType
EngineImageType
Visualisation contexts of vehicles and engines.
Definition: vehicle_type.h:87
Engine::flags
byte flags
Flags of the engine.
Definition: engine_base.h:35
_cur_year
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
HELILANDING
Helicopter wants to land.
Definition: airport.h:80
VehicleCargoList::StoredCount
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:366
RoadVehicle::overtaking
byte overtaking
Set to RVSB_DRIVE_SIDE when overtaking, otherwise 0.
Definition: roadveh.h:92
SpecializedVehicle< Train, Type >::From
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1113
VehicleCache::cached_max_speed
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition: vehicle_base.h:123
SmallVector::End
const T * End() const
Get the pointer behind the last valid item (const)
Definition: smallvec_type.hpp:292
Vehicle::GetEngine
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:743
Engine::GetDefaultCargoType
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition: engine_base.h:81
Aircraft::IsNormalAircraft
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow. ...
Definition: aircraft.h:121
AMED_EXACTPOS
Go exactly to the destination coordinates.
Definition: airport.h:54
Direction
Direction
Defines the 8 directions on the map.
Definition: direction_type.h:26
ClampU
static uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition: math_func.hpp:184
SmallVector::Append
T * Append(uint to_add=1)
Append an item and return it.
Definition: smallvec_type.hpp:134
GroundVehicleCache::first_engine
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself.
Definition: ground_vehicle.hpp:45
AMED_HOLD
Holding pattern movement (above the airport).
Definition: airport.h:58
random_func.hpp
Pseudo random number generator.
RealSpriteGroup
Definition: newgrf_spritegroup.h:79
ResolverObject::root_spritegroup
const SpriteGroup * root_spritegroup
Root SpriteGroup to use for resolving.
Definition: newgrf_spritegroup.h:339
Vehicle::breakdown_ctr
byte breakdown_ctr
Counter for managing breakdown events.
Definition: vehicle_base.h:263
Vehicle::Move
Vehicle * Move(int n)
Get the vehicle at offset n of this vehicle chain.
Definition: vehicle_base.h:624
Vehicle::subtype
byte subtype
subtype (Filled with values from #EffectVehicles/#TrainSubTypes/#AircraftSubTypes) ...
Definition: vehicle_base.h:327
RoadVehicle
Buses, trucks and trams belong to this class.
Definition: roadveh.h:88
Vehicle::cargo_cap
uint16 cargo_cap
total capacity
Definition: vehicle_base.h:307
VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
VF_BUILT_AS_PROTOTYPE
Vehicle is a prototype (accepted as exclusive preview).
Definition: vehicle_base.h:46
AMED_SLOWTURN
Turn slowly (mostly used in the air).
Definition: airport.h:52
Vehicle::acceleration
byte acceleration
used by train & aircraft
Definition: vehicle_base.h:295
GetRegister
static uint32 GetRegister(uint i)
Gets the value of a so-called newgrf "register".
Definition: newgrf_spritegroup.h:30
VehicleResolverObject::WO_NONE
Resolve no wagon overrides.
Definition: newgrf_engine.h:52
SpriteGroup::Resolve
virtual const SpriteGroup * Resolve(ResolverObject &object) const
Base sprite group resolver.
Definition: newgrf_spritegroup.h:62
newgrf_spritegroup.h
Action 2 handling.
EngineIDMapping::internal_id
uint16 internal_id
The internal ID within the GRF file.
Definition: engine_base.h:150
Vehicle::IsPrimaryVehicle
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:434
Vehicle::unitnumber
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:291
RealSpriteGroup::loaded
const SpriteGroup ** loaded
List of loaded groups (can be SpriteIDs or Callback results)
Definition: newgrf_spritegroup.h:92
Vehicle::cargo_subtype
byte cargo_subtype
Used for livery refits (NewGRF variations)
Definition: vehicle_base.h:306
SmallVector::Length
uint Length() const
Get the number of items in the list.
Definition: smallvec_type.hpp:262
AircraftVehicleInfo::subtype
byte subtype
Type of aircraft.
Definition: engine_type.h:102
DIR_W
West.
Definition: direction_type.h:34
MapAircraftMovementAction
static byte MapAircraftMovementAction(const Aircraft *v)
Map OTTD aircraft movement states to TTDPatch style movement actions (VarAction 2 Variable 0xE6) This...
Definition: newgrf_engine.cpp:293
VehicleResolverObject::WO_UNCACHED
Resolve wagon overrides.
Definition: newgrf_engine.h:53
TERM7
Heading for terminal 7.
Definition: airport.h:82
Vehicle::GetGroundVehicleCache
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
Definition: vehicle.cpp:2797
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:63
CBID_VEHICLE_MODIFY_PROPERTY
Called to modify various vehicle properties.
Definition: newgrf_callbacks.h:161
VehicleResolverObject
Resolver for a vehicle (chain)
Definition: newgrf_engine.h:49
SpecializedVehicle::Next
T * Next() const
Get next vehicle in the chain.
Definition: vehicle_base.h:1028
TERM2
Heading for terminal 2.
Definition: airport.h:66
EF_SPRITE_STACK
Draw vehicle by stacking multiple sprites.
Definition: engine_type.h:161
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
VEHICLE_LENGTH
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
Definition: vehicle_type.h:78
Vehicle::IsArticulatedPart
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:891
safeguards.h
A number of safeguards to prevent using unsafe methods.
Vehicle::InvalidateNewGRFCacheOfChain
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle) ...
Definition: vehicle_base.h:461
SpriteGroup
Definition: newgrf_spritegroup.h:58
VehicleEnteredDepotThisTick
void VehicleEnteredDepotThisTick(Vehicle *v)
Adds a vehicle to the list of vehicles that visited a depot this tick.
Definition: vehicle.cpp:894
Vehicle::waiting_triggers
byte waiting_triggers
Triggers to be yet matched before rerandomizing the random bits.
Definition: vehicle_base.h:300
DirDiff
DirDiff
Enumeration for the difference between two directions.
Definition: direction_type.h:65
GetTargetAirportIfValid
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft&#39;s target station if v->target_airport is a valid station with airport.
Definition: aircraft_cmd.cpp:2064
NewGRFCache::position_same_id_length
uint32 position_same_id_length
Cache for NewGRF var 41.
Definition: vehicle_base.h:70
FillNewGRFVehicleCache
void FillNewGRFVehicleCache(const Vehicle *v)
Fill the grf_cache of the given vehicle.
Definition: newgrf_engine.cpp:1282
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:42
Vehicle::GetCurrentMaxSpeed
virtual int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
Definition: vehicle_base.h:493
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:305
Livery
Information about a particular livery.
Definition: livery.h:76
VEH_EFFECT
Effect vehicle type (smoke, explosions, sparks, bubbles)
Definition: vehicle_type.h:31
ReallocT
static T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type...
Definition: alloc_func.hpp:113
Vehicle::load_unload_ticks
uint16 load_unload_ticks
Ticks to wait before starting next cycle.
Definition: vehicle_base.h:325
LIT_ALL
static const byte LIT_ALL
Show the liveries of all companies.
Definition: livery.h:19
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:142
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:230
VehicleResolverObject::VehicleResolverObject
VehicleResolverObject(EngineID engine_type, const Vehicle *v, WagonOverride wagon_override, bool info_view=false, CallbackID callback=CBID_NO_CALLBACK, uint32 callback_param1=0, uint32 callback_param2=0)
Resolver of a vehicle (chain).
Definition: newgrf_engine.cpp:961
NCVV_CONSIST_CARGO_INFORMATION
This bit will be set if the NewGRF var 42 currently stored is valid.
Definition: vehicle_base.h:60
Vehicle::HasArticulatedPart
bool HasArticulatedPart() const
Check if an engine has an articulated part.
Definition: vehicle_base.h:900
RealSpriteGroup::loading
const SpriteGroup ** loading
List of loading groups (can be SpriteIDs or Callback results)
Definition: newgrf_spritegroup.h:93
DirDifference
static DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Definition: direction_func.h:70
HELIPAD3
Heading for helipad 3.
Definition: airport.h:84
VehicleSpriteSeq
Sprite sequence for a vehicle part.
Definition: vehicle_base.h:130
TERM3
Heading for terminal 3.
Definition: airport.h:67
GRFFile::cargo_map
uint8 cargo_map[NUM_CARGO]
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:126
CBID_VEHICLE_COLOUR_MAPPING
Called to determine if a specific colour map should be used for a vehicle instead of the default live...
Definition: newgrf_callbacks.h:128
STARTTAKEOFF
Airplane has arrived at a runway for take-off.
Definition: airport.h:74
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:70
AirportFTAClass::MovingData
const AirportMovingData * MovingData(byte position) const
Get movement data at a position.
Definition: airport.h:171
min
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:42
VSG_SCOPE_SELF
Resolved object itself.
Definition: newgrf_spritegroup.h:103
Vehicle::random_bits
byte random_bits
Bits used for determining which randomized variational spritegroups to use when drawing.
Definition: vehicle_base.h:299
Vehicle::breakdowns_since_last_service
byte breakdowns_since_last_service
Counter for the amount of breakdowns.
Definition: vehicle_base.h:265
Vehicle::reliability
uint16 reliability
Reliability.
Definition: vehicle_base.h:261
ORIGINAL_BASE_YEAR
static const Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: date_type.h:51
Vehicle::First
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:595
Vehicle::tick_counter
byte tick_counter
Increased by one for each tick.
Definition: vehicle_base.h:314
RoadVehicle::crashed_ctr
uint16 crashed_ctr
Animation counter when the vehicle has crashed.
Definition: roadveh.h:94
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:321
Ship
All ships have this type.
Definition: ship.h:24
Vehicle::build_year
Year build_year
Year the vehicle has been built.
Definition: vehicle_base.h:257
Engine
Definition: engine_base.h:23
Aircraft::state
byte state
State of the airport.
Definition: aircraft.h:79
ScopeResolver::GetVariable
virtual uint32 GetVariable(byte variable, uint32 parameter, bool *available) const
Get a variable value.
Definition: newgrf_spritegroup.cpp:112
Aircraft::turn_counter
byte turn_counter
Ticks between each turn to prevent > 45 degree turns.
Definition: aircraft.h:82
VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:139
VehicleScopeResolver::GetVariable
uint32 GetVariable(byte variable, uint32 parameter, bool *available) const
Get a variable value.
Definition: newgrf_engine.cpp:883
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:39
Train
&#39;Train&#39; is either a loco or a wagon.
Definition: train.h:88
NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:66
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
Vehicle::breakdown_chance
byte breakdown_chance
Current chance of breakdowns.
Definition: vehicle_base.h:266
NCVV_POSITION_IN_VEHICLE
This bit will be set if the NewGRF var 4D currently stored is valid.
Definition: vehicle_base.h:62
RealSpriteGroup::num_loading
byte num_loading
Number of loading groups.
Definition: newgrf_spritegroup.h:91
VRF_POWEREDWAGON
Wagon is powered.
Definition: train.h:29
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:174
ResolverObject::grffile
const GRFFile * grffile
GRFFile the resolved SpriteGroup belongs to.
Definition: newgrf_spritegroup.h:338
ClampToI32
static int32 ClampToI32(const int64 a)
Reduce a signed 64-bit int to a signed 32-bit one.
Definition: math_func.hpp:203
company_func.h
Functions related to companies.
NewGRFCache::company_information
uint32 company_information
Cache for NewGRF var 43.
Definition: vehicle_base.h:72
CBID_VEHICLE_32DAY_CALLBACK
Called for every vehicle every 32 days (not all on same date though).
Definition: newgrf_callbacks.h:146
GetTileRailType
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
Definition: rail.cpp:157
SmallVector::FindIndex
int FindIndex(const T &item) const
Search for the first occurrence of an item.
Definition: smallvec_type.hpp:195
Vehicle::IsGroundVehicle
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
Definition: vehicle_base.h:472
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:140
Order::GetDestination
DestinationID GetDestination() const
Gets the destination of this order.
Definition: order_base.h:96
Vehicle::subspeed
byte subspeed
fractional speed
Definition: vehicle_base.h:294
VRF_TOGGLE_REVERSE
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
Definition: train.h:33
EngineID
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:22
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
_current_company
CompanyByte _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
newgrf_cargo.h
Cargo support for NewGRFs.
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:582
Vehicle::date_of_last_service
Date date_of_last_service
Last date the vehicle had a service at a depot.
Definition: vehicle_base.h:260
LANDING
Airplane wants to land.
Definition: airport.h:78
NewGRFCache::consist_cargo_information
uint32 consist_cargo_information
Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF ...
Definition: vehicle_base.h:71
VSG_SCOPE_PARENT
Related object of the resolved one.
Definition: newgrf_spritegroup.h:104
VehicleResolverObject::WO_SELF
Resolve self-override (helicopter rotors and such).
Definition: newgrf_engine.h:55
EngineIDMapping::type
VehicleTypeByte type
The engine type.
Definition: engine_base.h:151
VehicleResolverObject::GetScope
ScopeResolver * GetScope(VarSpriteGroupScope scope=VSG_SCOPE_SELF, byte relative=0)
Get a resolver for the scope.
Definition: newgrf_engine.cpp:351
Vehicle::owner
OwnerByte owner
Which company owns the vehicle?
Definition: vehicle_base.h:273
NewGRFCache::position_in_vehicle
uint32 position_in_vehicle
Cache for NewGRF var 4D.
Definition: vehicle_base.h:73
grfmsg
void CDECL grfmsg(int severity, const char *str,...)
DEBUG() function dedicated to newGRF debugging messages Function is essentially the same as DEBUG(grf...
Definition: newgrf.cpp:375
ResolverObject::callback
CallbackID callback
Callback being resolved.
Definition: newgrf_spritegroup.h:328
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:34
TERM8
Heading for terminal 8.
Definition: airport.h:83
GetCompanyInfo
uint32 GetCompanyInfo(CompanyID owner, const Livery *l)
Returns company information like in vehicle var 43 or station var 43.
Definition: newgrf_commons.cpp:469
VRF_REVERSE_DIRECTION
Reverse the visible direction of the vehicle.
Definition: train.h:30
NCVV_END
End of the bits.
Definition: vehicle_base.h:63
GetReverseRailTypeTranslation
uint8 GetReverseRailTypeTranslation(RailType railtype, const GRFFile *grffile)
Perform a reverse railtype lookup to get the GRF internal ID.
Definition: newgrf_railtype.cpp:139
Vehicle::z_pos
int32 z_pos
z coordinate.
Definition: vehicle_base.h:270
VS_HIDDEN
Vehicle is not visible.
Definition: vehicle_base.h:32
ATP_TTDP_LARGE
Same as AT_LARGE.
Definition: newgrf_airport.h:85
Pool::PoolItem<&_company_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-NULL) Titem.
Definition: pool_type.hpp:235
GRFFilePropsBase::local_id
uint16 local_id
id defined by the grf file for this entity
Definition: newgrf_commons.h:319
TERM5
Heading for terminal 5.
Definition: airport.h:69
Vehicle::GetGRFID
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition: vehicle.cpp:763
ship.h
Base for ships.
TERM4
Heading for terminal 4.
Definition: airport.h:68
EnginePreSort
static int CDECL EnginePreSort(const EngineID *a, const EngineID *b)
Comparator function to sort engines via scope-GRFID and local ID.
Definition: newgrf_engine.cpp:1210
Vehicle::GetNumOrders
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
Definition: vehicle_base.h:688
GetVehicleCallback
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
Definition: newgrf_engine.cpp:1067
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:114
GroundVehicleCache::cached_veh_length
uint8 cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
Definition: ground_vehicle.hpp:46
Station::airport
Airport airport
Tile area the airport covers.
Definition: station_base.h:460
ChangeDirDiff
static DirDiff ChangeDirDiff(DirDiff d, DirDiff delta)
Applies two differences together.
Definition: direction_func.h:90
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:288
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:320
CargoSpec::bitnum
uint8 bitnum
Cargo bit number, is INVALID_CARGO for a non-used spec.
Definition: cargotype.h:57
VehicleResolverObject::ResolveReal
const SpriteGroup * ResolveReal(const RealSpriteGroup *group) const
Get the real sprites of the grf.
Definition: newgrf_engine.cpp:918
CallbackID
CallbackID
List of implemented NewGRF callbacks.
Definition: newgrf_callbacks.h:22
HELIPAD1
Heading for helipad 1.
Definition: airport.h:71
Vehicle::x_pos
int32 x_pos
x coordinate.
Definition: vehicle_base.h:268
HELIENDLANDING
Helicopter wants to finish landing.
Definition: airport.h:81
BaseConsist::vehicle_flags
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
Definition: base_consist.h:32
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:105
AMED_HELI_RAISE
Helicopter take-off.
Definition: airport.h:56
CBID_RANDOM_TRIGGER
Set when calling a randomizing trigger (almost undocumented).
Definition: newgrf_callbacks.h:27
NewGRFCache::cache_valid
uint8 cache_valid
Bitset that indicates which cache values are valid.
Definition: vehicle_base.h:74
INVALID_TILE
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:85
SmallVector::Get
const T * Get(uint index) const
Get the pointer to item "number" (const)
Definition: smallvec_type.hpp:313
AirportMovingData::flag
uint16 flag
special flags when moving towards the destination.
Definition: airport.h:135
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
Vehicle::y_pos
int32 y_pos
y coordinate.
Definition: vehicle_base.h:269
DIRDIFF_REVERSE
One direction is the opposite of the other one.
Definition: direction_type.h:69
PositionHelper
static uint32 PositionHelper(const Vehicle *v, bool consecutive)
Helper to get the position of a vehicle within a chain of vehicles.
Definition: newgrf_engine.cpp:429
PalSpriteID::sprite
SpriteID sprite
The &#39;real&#39; sprite.
Definition: gfx_type.h:25
station_base.h
Base classes/functions for stations.
Vehicle::vcache
VehicleCache vcache
Cache of often used vehicle values.
Definition: vehicle_base.h:330
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
QSortT
static void QSortT(T *base, uint num, int(CDECL *comparator)(const T *, const T *), bool desc=false)
Type safe qsort()
Definition: sort_func.hpp:28
VehicleScopeResolver::GetTriggers
uint32 GetTriggers() const
Get the triggers.
Definition: newgrf_engine.cpp:345
Vehicle::age
Date age
Age in days.
Definition: vehicle_base.h:258
BaseConsist::cur_real_order_index
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
Definition: base_consist.h:29
BaseVehicle::type
VehicleTypeByte type
Type of vehicle.
Definition: vehicle_type.h:54
ENDLANDING
Airplane wants to finish landing.
Definition: airport.h:79
ClampToU16
static uint16 ClampToU16(const uint64 a)
Reduce an unsigned 64-bit int to an unsigned 16-bit one.
Definition: math_func.hpp:215
Station
Station data structure.
Definition: station_base.h:446
Vehicle::grf_cache
NewGRFCache grf_cache
Cache of often used calculated NewGRF values.
Definition: vehicle_base.h:329
Vehicle::GetDisplayProfitLastYear
Money GetDisplayProfitLastYear() const
Gets the profit vehicle had last year.
Definition: vehicle_base.h:573
Vehicle::day_counter
byte day_counter
Increased by one for each day.
Definition: vehicle_base.h:313
GetRailType
static RailType GetRailType(TileIndex t)
Gets the rail type of the given tile.
Definition: rail_map.h:116
AirportFTAClass::delta_z
byte delta_z
Z adjustment for helicopter pads.
Definition: airport.h:184
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:318
VehicleScopeResolver::GetRandomBits
uint32 GetRandomBits() const
Get a few random bits.
Definition: newgrf_engine.cpp:340
GroundVehicle::IsEngine
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
Definition: ground_vehicle.hpp:318
GroundVehicle::gcache
GroundVehicleCache gcache
Cache of often calculated values.
Definition: ground_vehicle.hpp:82
RoadVehicle::overtaking_ctr
byte overtaking_ctr
The length of the current overtake attempt.
Definition: roadveh.h:93
GRFFile
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:104
VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
HELITAKEOFF
Helicopter wants to leave the airport.
Definition: airport.h:76
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:26
SetEngineGRF
void SetEngineGRF(EngineID engine, const GRFFile *file)
Tie a GRFFile entry to an engine, to allow us to retrieve GRF parameters etc during a game...
Definition: newgrf_engine.cpp:104
VehicleResolverObject::WO_CACHED
Resolve wagon overrides using TrainCache::cached_override.
Definition: newgrf_engine.h:54