OpenTTD
roadveh_cmd.cpp
Go to the documentation of this file.
1 /* $Id: roadveh_cmd.cpp 27134 2015-02-01 20:54:24Z 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 "roadveh.h"
14 #include "command_func.h"
15 #include "news_func.h"
17 #include "station_base.h"
18 #include "company_func.h"
19 #include "articulated_vehicles.h"
20 #include "newgrf_sound.h"
21 #include "pathfinder/yapf/yapf.h"
22 #include "strings_func.h"
23 #include "tunnelbridge_map.h"
24 #include "date_func.h"
25 #include "vehicle_func.h"
26 #include "sound_func.h"
27 #include "ai/ai.hpp"
28 #include "game/game.hpp"
29 #include "depot_map.h"
30 #include "effectvehicle_func.h"
31 #include "roadstop_base.h"
32 #include "spritecache.h"
33 #include "core/random_func.hpp"
34 #include "company_base.h"
35 #include "core/backup_type.hpp"
36 #include "newgrf.h"
37 #include "zoom_func.h"
38 
39 #include "table/strings.h"
40 
41 #include "safeguards.h"
42 
43 static const uint16 _roadveh_images[] = {
44  0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
45  0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
46  0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
47  0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
48  0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
49  0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
50  0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
51  0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
52 };
53 
54 static const uint16 _roadveh_full_adder[] = {
55  0, 88, 0, 0, 0, 0, 48, 48,
56  48, 48, 0, 0, 64, 64, 0, 16,
57  16, 0, 88, 0, 0, 0, 0, 48,
58  48, 48, 48, 0, 0, 64, 64, 0,
59  16, 16, 0, 88, 0, 0, 0, 0,
60  48, 48, 48, 48, 0, 0, 64, 64,
61  0, 16, 16, 0, 8, 8, 8, 8,
62  0, 0, 0, 8, 8, 8, 8
63 };
64 assert_compile(lengthof(_roadveh_images) == lengthof(_roadveh_full_adder));
65 
66 template <>
67 bool IsValidImageIndex<VEH_ROAD>(uint8 image_index)
68 {
69  return image_index < lengthof(_roadveh_images);
70 }
71 
74  TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_LOWER_E | TRACKDIR_BIT_X_NE, // Enter from north east
75  TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_UPPER_E | TRACKDIR_BIT_Y_SE, // Enter from south east
76  TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_RIGHT_S, // Enter from south west
78 };
79 
80 static const Trackdir _road_reverse_table[DIAGDIR_END] = {
82 };
83 
87 };
88 
89 
94 bool RoadVehicle::IsBus() const
95 {
96  assert(this->IsFrontEngine());
98 }
99 
106 {
107  int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
108 
109  if (offset != NULL) {
110  offset->x = ScaleGUITrad(reference_width) / 2;
111  offset->y = 0;
112  }
113  return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
114 }
115 
116 static SpriteID GetRoadVehIcon(EngineID engine, EngineImageType image_type)
117 {
118  const Engine *e = Engine::Get(engine);
119  uint8 spritenum = e->u.road.image_index;
120 
121  if (is_custom_sprite(spritenum)) {
122  SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W, image_type);
123  if (sprite != 0) return sprite;
124 
125  spritenum = e->original_image_index;
126  }
127 
128  assert(IsValidImageIndex<VEH_ROAD>(spritenum));
129  return DIR_W + _roadveh_images[spritenum];
130 }
131 
133 {
134  uint8 spritenum = this->spritenum;
135  SpriteID sprite;
136 
137  if (is_custom_sprite(spritenum)) {
138  sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
139  if (sprite != 0) return sprite;
140 
141  spritenum = this->GetEngine()->original_image_index;
142  }
143 
144  assert(IsValidImageIndex<VEH_ROAD>(spritenum));
145  sprite = direction + _roadveh_images[spritenum];
146 
147  if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _roadveh_full_adder[spritenum];
148 
149  return sprite;
150 }
151 
161 void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
162 {
163  SpriteID sprite = GetRoadVehIcon(engine, image_type);
164  const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
165  preferred_x = Clamp(preferred_x,
166  left - UnScaleGUI(real_sprite->x_offs),
167  right - UnScaleGUI(real_sprite->width) - UnScaleGUI(real_sprite->x_offs));
168  DrawSprite(sprite, pal, preferred_x, y);
169 }
170 
180 void GetRoadVehSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
181 {
182  const Sprite *spr = GetSprite(GetRoadVehIcon(engine, image_type), ST_NORMAL);
183 
184  width = UnScaleGUI(spr->width);
185  height = UnScaleGUI(spr->height);
186  xoffs = UnScaleGUI(spr->x_offs);
187  yoffs = UnScaleGUI(spr->y_offs);
188 }
189 
195 static uint GetRoadVehLength(const RoadVehicle *v)
196 {
197  const Engine *e = v->GetEngine();
198  uint length = VEHICLE_LENGTH;
199 
200  uint16 veh_len = CALLBACK_FAILED;
201  if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
202  /* Use callback 36 */
203  veh_len = GetVehicleProperty(v, PROP_ROADVEH_SHORTEN_FACTOR, CALLBACK_FAILED);
204  if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
205  } else {
206  /* Use callback 11 */
207  veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
208  }
209  if (veh_len == CALLBACK_FAILED) veh_len = e->u.road.shorten_factor;
210  if (veh_len != 0) {
211  length -= Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
212  }
213 
214  return length;
215 }
216 
223 void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
224 {
225  assert(v->type == VEH_ROAD);
226  assert(v->IsFrontEngine());
227 
229 
231 
232  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
233  /* Check the v->first cache. */
234  assert(u->First() == v);
235 
236  /* Update the 'first engine' */
237  u->gcache.first_engine = (v == u) ? INVALID_ENGINE : v->engine_type;
238 
239  /* Update the length of the vehicle. */
240  uint veh_len = GetRoadVehLength(u);
241  /* Verify length hasn't changed. */
242  if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
243 
244  u->gcache.cached_veh_length = veh_len;
245  v->gcache.cached_total_length += u->gcache.cached_veh_length;
246 
247  /* Update visual effect */
248  u->UpdateVisualEffect();
249 
250  /* Update cargo aging period. */
251  u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_ROADVEH_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
252  }
253 
254  uint max_speed = GetVehicleProperty(v, PROP_ROADVEH_SPEED, 0);
255  v->vcache.cached_max_speed = (max_speed != 0) ? max_speed * 4 : RoadVehInfo(v->engine_type)->max_speed;
256 }
257 
268 {
269  if (HasTileRoadType(tile, ROADTYPE_TRAM) != HasBit(e->info.misc_flags, EF_ROAD_TRAM)) return_cmd_error(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE);
270 
271  if (flags & DC_EXEC) {
272  const RoadVehicleInfo *rvi = &e->u.road;
273 
274  RoadVehicle *v = new RoadVehicle();
275  *ret = v;
277  v->owner = _current_company;
278 
279  v->tile = tile;
280  int x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
281  int y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
282  v->x_pos = x;
283  v->y_pos = y;
284  v->z_pos = GetSlopePixelZ(x, y);
285 
286  v->state = RVSB_IN_DEPOT;
288 
289  v->spritenum = rvi->image_index;
291  v->cargo_cap = rvi->capacity;
292  v->refit_cap = 0;
293 
294  v->last_station_visited = INVALID_STATION;
295  v->last_loading_station = INVALID_STATION;
296  v->engine_type = e->index;
297  v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
298 
299  v->reliability = e->reliability;
301  v->max_age = e->GetLifeLengthInDays();
302  _new_vehicle_id = v->index;
303 
304  v->SetServiceInterval(Company::Get(v->owner)->settings.vehicle.servint_roadveh);
305 
307  v->build_year = _cur_year;
308 
309  v->cur_image = SPR_IMG_QUERY;
311  v->SetFrontEngine();
312 
313  v->roadtype = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
314  v->compatible_roadtypes = RoadTypeToRoadTypes(v->roadtype);
316 
318  v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
319 
322 
323  /* Call various callbacks after the whole consist has been constructed */
324  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
325  u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
326  u->refit_cap = 0;
328  u->InvalidateNewGRFCache();
329  }
331  /* Initialize cached values for realistic acceleration. */
333 
334  v->UpdatePosition();
335 
337  }
338 
339  return CommandCost();
340 }
341 
342 static FindDepotData FindClosestRoadDepot(const RoadVehicle *v, int max_distance)
343 {
344  if (IsRoadDepotTile(v->tile)) return FindDepotData(v->tile, 0);
345 
347  case VPF_NPF: return NPFRoadVehicleFindNearestDepot(v, max_distance);
348  case VPF_YAPF: return YapfRoadVehicleFindNearestDepot(v, max_distance);
349 
350  default: NOT_REACHED();
351  }
352 }
353 
354 bool RoadVehicle::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
355 {
356  FindDepotData rfdd = FindClosestRoadDepot(this, 0);
357  if (rfdd.best_length == UINT_MAX) return false;
358 
359  if (location != NULL) *location = rfdd.tile;
360  if (destination != NULL) *destination = GetDepotIndex(rfdd.tile);
361 
362  return true;
363 }
364 
374 CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
375 {
377  if (v == NULL) return CMD_ERROR;
378 
379  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
380 
381  CommandCost ret = CheckOwnership(v->owner);
382  if (ret.Failed()) return ret;
383 
384  if ((v->vehstatus & VS_STOPPED) ||
385  (v->vehstatus & VS_CRASHED) ||
386  v->breakdown_ctr != 0 ||
387  v->overtaking != 0 ||
388  v->state == RVSB_WORMHOLE ||
389  v->IsInDepot() ||
390  v->current_order.IsType(OT_LOADING)) {
391  return CMD_ERROR;
392  }
393 
395 
397 
398  if (flags & DC_EXEC) v->reverse_ctr = 180;
399 
400  return CommandCost();
401 }
402 
403 
405 {
406  for (RoadVehicle *v = this; v != NULL; v = v->Next()) {
407  v->colourmap = PAL_NONE;
408  v->UpdateViewport(true, false);
409  }
410  this->CargoChanged();
411 }
412 
414 {
415  static const int8 _delta_xy_table[8][10] = {
416  /* y_extent, x_extent, y_offs, x_offs, y_bb_offs, x_bb_offs, y_extent_shorten, x_extent_shorten, y_bb_offs_shorten, x_bb_offs_shorten */
417  {3, 3, -1, -1, 0, 0, -1, -1, -1, -1}, // N
418  {3, 7, -1, -3, 0, -1, 0, -1, 0, 0}, // NE
419  {3, 3, -1, -1, 0, 0, 1, -1, 1, -1}, // E
420  {7, 3, -3, -1, -1, 0, 0, 0, 1, 0}, // SE
421  {3, 3, -1, -1, 0, 0, 1, 1, 1, 1}, // S
422  {3, 7, -1, -3, 0, -1, 0, 0, 0, 1}, // SW
423  {3, 3, -1, -1, 0, 0, -1, 1, -1, 1}, // W
424  {7, 3, -3, -1, -1, 0, -1, 0, 0, 0}, // NW
425  };
426 
427  int shorten = VEHICLE_LENGTH - this->gcache.cached_veh_length;
428  if (!IsDiagonalDirection(direction)) shorten >>= 1;
429 
430  const int8 *bb = _delta_xy_table[direction];
431  this->x_bb_offs = bb[5] + bb[9] * shorten;
432  this->y_bb_offs = bb[4] + bb[8] * shorten;;
433  this->x_offs = bb[3];
434  this->y_offs = bb[2];
435  this->x_extent = bb[1] + bb[7] * shorten;
436  this->y_extent = bb[0] + bb[6] * shorten;
437  this->z_extent = 6;
438 }
439 
445 {
446  int max_speed = this->vcache.cached_max_speed;
447 
448  /* Limit speed to 50% while reversing, 75% in curves. */
449  for (const RoadVehicle *u = this; u != NULL; u = u->Next()) {
450  if (_settings_game.vehicle.roadveh_acceleration_model == AM_REALISTIC) {
452  max_speed = this->vcache.cached_max_speed / 2;
453  break;
454  } else if ((u->direction & 1) == 0) {
455  max_speed = this->vcache.cached_max_speed * 3 / 4;
456  }
457  }
458 
459  /* Vehicle is on the middle part of a bridge. */
460  if (u->state == RVSB_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
461  max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed * 2);
462  }
463  }
464 
465  return min(max_speed, this->current_order.GetMaxSpeed() * 2);
466 }
467 
473 {
474  RoadVehicle *first = v->First();
475  Vehicle *u = v;
476  for (; v->Next() != NULL; v = v->Next()) u = v;
477  u->SetNext(NULL);
478  v->last_station_visited = first->last_station_visited; // for PreDestructor
479 
480  /* Only leave the road stop when we're really gone. */
481  if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
482 
483  delete v;
484 }
485 
486 static void RoadVehSetRandomDirection(RoadVehicle *v)
487 {
488  static const DirDiff delta[] = {
490  };
491 
492  do {
493  uint32 r = Random();
494 
495  v->direction = ChangeDir(v->direction, delta[r & 3]);
496  v->UpdateViewport(true, true);
497  } while ((v = v->Next()) != NULL);
498 }
499 
506 {
507  v->crashed_ctr++;
508  if (v->crashed_ctr == 2) {
510  } else if (v->crashed_ctr <= 45) {
511  if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
512  } else if (v->crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
513  bool ret = v->Next() != NULL;
515  return ret;
516  }
517 
518  return true;
519 }
520 
528 {
529  const Vehicle *u = (Vehicle*)data;
530 
531  return (v->type == VEH_TRAIN &&
532  abs(v->z_pos - u->z_pos) <= 6 &&
533  abs(v->x_pos - u->x_pos) <= 4 &&
534  abs(v->y_pos - u->y_pos) <= 4) ? v : NULL;
535 }
536 
537 uint RoadVehicle::Crash(bool flooded)
538 {
539  uint pass = this->GroundVehicleBase::Crash(flooded);
540  if (this->IsFrontEngine()) {
541  pass += 1; // driver
542 
543  /* If we're in a drive through road stop we ought to leave it */
544  if (IsInsideMM(this->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
545  RoadStop::GetByTile(this->tile, GetRoadStopType(this->tile))->Leave(this);
546  }
547  }
548  this->crashed_ctr = flooded ? 2000 : 1; // max 2220, disappear pretty fast when flooded
549  return pass;
550 }
551 
552 static void RoadVehCrash(RoadVehicle *v)
553 {
554  uint pass = v->Crash();
555 
556  AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
557  Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
558 
559  SetDParam(0, pass);
561  (pass == 1) ?
562  STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER : STR_NEWS_ROAD_VEHICLE_CRASH,
563  NT_ACCIDENT,
564  v->index
565  );
566 
567  ModifyStationRatingAround(v->tile, v->owner, -160, 22);
568  if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
569 }
570 
571 static bool RoadVehCheckTrainCrash(RoadVehicle *v)
572 {
573  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
574  if (u->state == RVSB_WORMHOLE) continue;
575 
576  TileIndex tile = u->tile;
577 
578  if (!IsLevelCrossingTile(tile)) continue;
579 
581  RoadVehCrash(v);
582  return true;
583  }
584  }
585 
586  return false;
587 }
588 
590 {
591  if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
592 
593  const Station *st = Station::Get(station);
594  if (!CanVehicleUseStation(this, st)) {
595  /* There is no stop left at the station, so don't even TRY to go there */
596  this->IncrementRealOrderIndex();
597  return 0;
598  }
599 
600  return st->xy;
601 }
602 
603 static void StartRoadVehSound(const RoadVehicle *v)
604 {
605  if (!PlayVehicleSound(v, VSE_START)) {
606  SoundID s = RoadVehInfo(v->engine_type)->sfx;
607  if (s == SND_19_BUS_START_PULL_AWAY && (v->tick_counter & 3) == 0) {
608  s = SND_1A_BUS_START_PULL_AWAY_WITH_HORN;
609  }
610  SndPlayVehicleFx(s, v);
611  }
612 }
613 
615  int x;
616  int y;
617  const Vehicle *veh;
618  Vehicle *best;
619  uint best_diff;
620  Direction dir;
621 };
622 
623 static Vehicle *EnumCheckRoadVehClose(Vehicle *v, void *data)
624 {
625  static const int8 dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
626  static const int8 dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
627 
628  RoadVehFindData *rvf = (RoadVehFindData*)data;
629 
630  short x_diff = v->x_pos - rvf->x;
631  short y_diff = v->y_pos - rvf->y;
632 
633  if (v->type == VEH_ROAD &&
634  !v->IsInDepot() &&
635  abs(v->z_pos - rvf->veh->z_pos) < 6 &&
636  v->direction == rvf->dir &&
637  rvf->veh->First() != v->First() &&
638  (dist_x[v->direction] >= 0 || (x_diff > dist_x[v->direction] && x_diff <= 0)) &&
639  (dist_x[v->direction] <= 0 || (x_diff < dist_x[v->direction] && x_diff >= 0)) &&
640  (dist_y[v->direction] >= 0 || (y_diff > dist_y[v->direction] && y_diff <= 0)) &&
641  (dist_y[v->direction] <= 0 || (y_diff < dist_y[v->direction] && y_diff >= 0))) {
642  uint diff = abs(x_diff) + abs(y_diff);
643 
644  if (diff < rvf->best_diff || (diff == rvf->best_diff && v->index < rvf->best->index)) {
645  rvf->best = v;
646  rvf->best_diff = diff;
647  }
648  }
649 
650  return NULL;
651 }
652 
653 static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction dir, bool update_blocked_ctr = true)
654 {
655  RoadVehFindData rvf;
656  RoadVehicle *front = v->First();
657 
658  if (front->reverse_ctr != 0) return NULL;
659 
660  rvf.x = x;
661  rvf.y = y;
662  rvf.dir = dir;
663  rvf.veh = v;
664  rvf.best_diff = UINT_MAX;
665 
666  if (front->state == RVSB_WORMHOLE) {
667  FindVehicleOnPos(v->tile, &rvf, EnumCheckRoadVehClose);
668  FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &rvf, EnumCheckRoadVehClose);
669  } else {
670  FindVehicleOnPosXY(x, y, &rvf, EnumCheckRoadVehClose);
671  }
672 
673  /* This code protects a roadvehicle from being blocked for ever
674  * If more than 1480 / 74 days a road vehicle is blocked, it will
675  * drive just through it. The ultimate backup-code of TTD.
676  * It can be disabled. */
677  if (rvf.best_diff == UINT_MAX) {
678  front->blocked_ctr = 0;
679  return NULL;
680  }
681 
682  if (update_blocked_ctr && ++front->blocked_ctr > 1480) return NULL;
683 
684  return RoadVehicle::From(rvf.best);
685 }
686 
692 static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
693 {
694  if (v->IsBus()) {
695  /* Check if station was ever visited before */
696  if (!(st->had_vehicle_of_type & HVOT_BUS)) {
697  st->had_vehicle_of_type |= HVOT_BUS;
698  SetDParam(0, st->index);
700  v->roadtype == ROADTYPE_ROAD ? STR_NEWS_FIRST_BUS_ARRIVAL : STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL,
702  v->index,
703  st->index
704  );
705  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
706  Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
707  }
708  } else {
709  /* Check if station was ever visited before */
710  if (!(st->had_vehicle_of_type & HVOT_TRUCK)) {
711  st->had_vehicle_of_type |= HVOT_TRUCK;
712  SetDParam(0, st->index);
714  v->roadtype == ROADTYPE_ROAD ? STR_NEWS_FIRST_TRUCK_ARRIVAL : STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL,
716  v->index,
717  st->index
718  );
719  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
720  Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
721  }
722  }
723 }
724 
733 {
735  default: NOT_REACHED();
736  case AM_ORIGINAL:
737  return this->DoUpdateSpeed(this->overtaking != 0 ? 512 : 256, 0, this->GetCurrentMaxSpeed());
738 
739  case AM_REALISTIC:
740  return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking != 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 4, this->GetCurrentMaxSpeed());
741  }
742 }
743 
744 static Direction RoadVehGetNewDirection(const RoadVehicle *v, int x, int y)
745 {
746  static const Direction _roadveh_new_dir[] = {
749  DIR_E , DIR_SE, DIR_S
750  };
751 
752  x = x - v->x_pos + 1;
753  y = y - v->y_pos + 1;
754 
755  if ((uint)x > 2 || (uint)y > 2) return v->direction;
756  return _roadveh_new_dir[y * 4 + x];
757 }
758 
759 static Direction RoadVehGetSlidingDirection(const RoadVehicle *v, int x, int y)
760 {
761  Direction new_dir = RoadVehGetNewDirection(v, x, y);
762  Direction old_dir = v->direction;
763  DirDiff delta;
764 
765  if (new_dir == old_dir) return old_dir;
766  delta = (DirDifference(new_dir, old_dir) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
767  return ChangeDir(old_dir, delta);
768 }
769 
770 struct OvertakeData {
771  const RoadVehicle *u;
772  const RoadVehicle *v;
773  TileIndex tile;
774  Trackdir trackdir;
775 };
776 
777 static Vehicle *EnumFindVehBlockingOvertake(Vehicle *v, void *data)
778 {
779  const OvertakeData *od = (OvertakeData*)data;
780 
781  return (v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v) ? v : NULL;
782 }
783 
791 {
792  TrackStatus ts = GetTileTrackStatus(od->tile, TRANSPORT_ROAD, od->v->compatible_roadtypes);
793  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts);
794  TrackdirBits red_signals = TrackStatusToRedSignals(ts); // barred level crossing
795  TrackBits trackbits = TrackdirBitsToTrackBits(trackdirbits);
796 
797  /* Track does not continue along overtaking direction || track has junction || levelcrossing is barred */
798  if (!HasBit(trackdirbits, od->trackdir) || (trackbits & ~TRACK_BIT_CROSS) || (red_signals != TRACKDIR_BIT_NONE)) return true;
799 
800  /* Are there more vehicles on the tile except the two vehicles involved in overtaking */
801  return HasVehicleOnPos(od->tile, od, EnumFindVehBlockingOvertake);
802 }
803 
804 static void RoadVehCheckOvertake(RoadVehicle *v, RoadVehicle *u)
805 {
806  OvertakeData od;
807 
808  od.v = v;
809  od.u = u;
810 
811  /* Trams can't overtake other trams */
812  if (v->roadtype == ROADTYPE_TRAM) return;
813 
814  /* Don't overtake in stations */
815  if (IsTileType(v->tile, MP_STATION) || IsTileType(u->tile, MP_STATION)) return;
816 
817  /* For now, articulated road vehicles can't overtake anything. */
818  if (v->HasArticulatedPart()) return;
819 
820  /* Vehicles are not driving in same direction || direction is not a diagonal direction */
821  if (v->direction != u->direction || !(v->direction & 1)) return;
822 
823  /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
825 
826  /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
827  * accelerating, take the maximum speed for the comparison, else the current speed. */
828  int u_speed = u->GetAcceleration() > 0 ? u->GetCurrentMaxSpeed() : u->cur_speed;
829  if (u_speed >= v->GetCurrentMaxSpeed() &&
830  !(u->vehstatus & VS_STOPPED) &&
831  u->cur_speed != 0) {
832  return;
833  }
834 
835  od.trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
836 
837  /* Are the current and the next tile suitable for overtaking?
838  * - Does the track continue along od.trackdir
839  * - No junctions
840  * - No barred levelcrossing
841  * - No other vehicles in the way
842  */
843  od.tile = v->tile;
844  if (CheckRoadBlockedForOvertaking(&od)) return;
845 
846  od.tile = v->tile + TileOffsByDiagDir(DirToDiagDir(v->direction));
847  if (CheckRoadBlockedForOvertaking(&od)) return;
848 
849  /* When the vehicle in front of us is stopped we may only take
850  * half the time to pass it than when the vehicle is moving. */
851  v->overtaking_ctr = (od.u->cur_speed == 0 || (od.u->vehstatus & VS_STOPPED)) ? RV_OVERTAKE_TIMEOUT / 2 : 0;
853 }
854 
855 static void RoadZPosAffectSpeed(RoadVehicle *v, int old_z)
856 {
857  if (old_z == v->z_pos || _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) return;
858 
859  if (old_z < v->z_pos) {
860  v->cur_speed = v->cur_speed * 232 / 256; // slow down by ~10%
861  } else {
862  uint16 spd = v->cur_speed + 2;
863  if (spd <= v->vcache.cached_max_speed) v->cur_speed = spd;
864  }
865 }
866 
867 static int PickRandomBit(uint bits)
868 {
869  uint i;
870  uint num = RandomRange(CountBits(bits));
871 
872  for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {}
873  return i;
874 }
875 
885 {
886 #define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
887 
888  TileIndex desttile;
889  Trackdir best_track;
890  bool path_found = true;
891 
892  TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_ROAD, v->compatible_roadtypes);
893  TrackdirBits red_signals = TrackStatusToRedSignals(ts); // crossing
894  TrackdirBits trackdirs = TrackStatusToTrackdirBits(ts);
895 
896  if (IsTileType(tile, MP_ROAD)) {
897  if (IsRoadDepot(tile) && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir || (GetRoadTypes(tile) & v->compatible_roadtypes) == 0)) {
898  /* Road depot owned by another company or with the wrong orientation */
899  trackdirs = TRACKDIR_BIT_NONE;
900  }
901  } else if (IsTileType(tile, MP_STATION) && IsStandardRoadStopTile(tile)) {
902  /* Standard road stop (drive-through stops are treated as normal road) */
903 
904  if (!IsTileOwner(tile, v->owner) || GetRoadStopDir(tile) == enterdir || v->HasArticulatedPart()) {
905  /* different station owner or wrong orientation or the vehicle has articulated parts */
906  trackdirs = TRACKDIR_BIT_NONE;
907  } else {
908  /* Our station */
909  RoadStopType rstype = v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK;
910 
911  if (GetRoadStopType(tile) != rstype) {
912  /* Wrong station type */
913  trackdirs = TRACKDIR_BIT_NONE;
914  } else {
915  /* Proper station type, check if there is free loading bay */
917  !RoadStop::GetByTile(tile, rstype)->HasFreeBay()) {
918  /* Station is full and RV queuing is off */
919  trackdirs = TRACKDIR_BIT_NONE;
920  }
921  }
922  }
923  }
924  /* The above lookups should be moved to GetTileTrackStatus in the
925  * future, but that requires more changes to the pathfinder and other
926  * stuff, probably even more arguments to GTTS.
927  */
928 
929  /* Remove tracks unreachable from the enter dir */
930  trackdirs &= _road_enter_dir_to_reachable_trackdirs[enterdir];
931  if (trackdirs == TRACKDIR_BIT_NONE) {
932  /* No reachable tracks, so we'll reverse */
933  return_track(_road_reverse_table[enterdir]);
934  }
935 
936  if (v->reverse_ctr != 0) {
937  bool reverse = true;
938  if (v->roadtype == ROADTYPE_TRAM) {
939  /* Trams may only reverse on a tile if it contains at least the straight
940  * trackbits or when it is a valid turning tile (i.e. one roadbit) */
942  RoadBits straight = AxisToRoadBits(DiagDirToAxis(enterdir));
943  reverse = ((rb & straight) == straight) ||
944  (rb == DiagDirToRoadBits(enterdir));
945  }
946  if (reverse) {
947  v->reverse_ctr = 0;
948  if (v->tile != tile) {
949  return_track(_road_reverse_table[enterdir]);
950  }
951  }
952  }
953 
954  desttile = v->dest_tile;
955  if (desttile == 0) {
956  /* We've got no destination, pick a random track */
957  return_track(PickRandomBit(trackdirs));
958  }
959 
960  /* Only one track to choose between? */
961  if (KillFirstBit(trackdirs) == TRACKDIR_BIT_NONE) {
962  return_track(FindFirstBit2x64(trackdirs));
963  }
964 
966  case VPF_NPF: best_track = NPFRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
967  case VPF_YAPF: best_track = YapfRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
968 
969  default: NOT_REACHED();
970  }
971  v->HandlePathfindingResult(path_found);
972 
973 found_best_track:;
974 
975  if (HasBit(red_signals, best_track)) return INVALID_TRACKDIR;
976 
977  return best_track;
978 }
979 
981  byte x, y;
982 };
983 
984 #include "table/roadveh_movement.h"
985 
986 static bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
987 {
988  /* Don't leave unless v and following wagons are in the depot. */
989  for (const RoadVehicle *u = v; u != NULL; u = u->Next()) {
990  if (u->state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
991  }
992 
994  v->direction = DiagDirToDir(dir);
995 
996  Trackdir tdir = _roadveh_depot_exit_trackdir[dir];
997  const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + tdir];
998 
999  int x = TileX(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].x & 0xF);
1000  int y = TileY(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].y & 0xF);
1001 
1002  if (first) {
1003  /* We are leaving a depot, but have to go to the exact same one; re-enter */
1004  if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
1005  VehicleEnterDepot(v);
1006  return true;
1007  }
1008 
1009  if (RoadVehFindCloseTo(v, x, y, v->direction, false) != NULL) return true;
1010 
1012 
1013  StartRoadVehSound(v);
1014 
1015  /* Vehicle is about to leave a depot */
1016  v->cur_speed = 0;
1017  }
1018 
1019  v->vehstatus &= ~VS_HIDDEN;
1020  v->state = tdir;
1021  v->frame = RVC_DEPOT_START_FRAME;
1022 
1023  v->x_pos = x;
1024  v->y_pos = y;
1025  v->UpdatePosition();
1026  v->UpdateInclination(true, true);
1027 
1029 
1030  return true;
1031 }
1032 
1033 static Trackdir FollowPreviousRoadVehicle(const RoadVehicle *v, const RoadVehicle *prev, TileIndex tile, DiagDirection entry_dir, bool already_reversed)
1034 {
1035  if (prev->tile == v->tile && !already_reversed) {
1036  /* If the previous vehicle is on the same tile as this vehicle is
1037  * then it must have reversed. */
1038  return _road_reverse_table[entry_dir];
1039  }
1040 
1041  byte prev_state = prev->state;
1042  Trackdir dir;
1043 
1044  if (prev_state == RVSB_WORMHOLE || prev_state == RVSB_IN_DEPOT) {
1045  DiagDirection diag_dir = INVALID_DIAGDIR;
1046 
1047  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1048  diag_dir = GetTunnelBridgeDirection(tile);
1049  } else if (IsRoadDepotTile(tile)) {
1050  diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
1051  }
1052 
1053  if (diag_dir == INVALID_DIAGDIR) return INVALID_TRACKDIR;
1054  dir = DiagDirToDiagTrackdir(diag_dir);
1055  } else {
1056  if (already_reversed && prev->tile != tile) {
1057  /*
1058  * The vehicle has reversed, but did not go straight back.
1059  * It immediately turn onto another tile. This means that
1060  * the roadstate of the previous vehicle cannot be used
1061  * as the direction we have to go with this vehicle.
1062  *
1063  * Next table is build in the following way:
1064  * - first row for when the vehicle in front went to the northern or
1065  * western tile, second for southern and eastern.
1066  * - columns represent the entry direction.
1067  * - cell values are determined by the Trackdir one has to take from
1068  * the entry dir (column) to the tile in north or south by only
1069  * going over the trackdirs used for turning 90 degrees, i.e.
1070  * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1071  */
1072  static const Trackdir reversed_turn_lookup[2][DIAGDIR_END] = {
1075  dir = reversed_turn_lookup[prev->tile < tile ? 0 : 1][ReverseDiagDir(entry_dir)];
1076  } else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) {
1077  dir = (Trackdir)(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK);
1078  } else if (prev_state < TRACKDIR_END) {
1079  dir = (Trackdir)prev_state;
1080  } else {
1081  return INVALID_TRACKDIR;
1082  }
1083  }
1084 
1085  /* Do some sanity checking. */
1086  static const RoadBits required_roadbits[] = {
1088  ROAD_NW | ROAD_SW, ROAD_NE | ROAD_SE, ROAD_X, ROAD_Y
1089  };
1090  RoadBits required = required_roadbits[dir & 0x07];
1091 
1092  if ((required & GetAnyRoadBits(tile, v->roadtype, true)) == ROAD_NONE) {
1093  dir = INVALID_TRACKDIR;
1094  }
1095 
1096  return dir;
1097 }
1098 
1107 {
1108  /* The 'current' company is not necessarily the owner of the vehicle. */
1109  Backup<CompanyByte> cur_company(_current_company, c, FILE_LINE);
1110 
1112 
1113  cur_company.Restore();
1114  return ret.Succeeded();
1115 }
1116 
1117 bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev)
1118 {
1119  if (v->overtaking != 0) {
1120  if (IsTileType(v->tile, MP_STATION)) {
1121  /* Force us to be not overtaking! */
1122  v->overtaking = 0;
1123  } else if (++v->overtaking_ctr >= RV_OVERTAKE_TIMEOUT) {
1124  /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1125  * if the vehicle started a corner. To protect that, only allow an abort of
1126  * overtake if we are on straight roads */
1128  v->overtaking = 0;
1129  }
1130  }
1131  }
1132 
1133  /* If this vehicle is in a depot and we've reached this point it must be
1134  * one of the articulated parts. It will stay in the depot until activated
1135  * by the previous vehicle in the chain when it gets to the right place. */
1136  if (v->IsInDepot()) return true;
1137 
1138  if (v->state == RVSB_WORMHOLE) {
1139  /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1141 
1142  if (v->IsFrontEngine()) {
1143  const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
1144  if (u != NULL) {
1145  v->cur_speed = u->First()->cur_speed;
1146  return false;
1147  }
1148  }
1149 
1151  /* Vehicle has just entered a bridge or tunnel */
1152  v->x_pos = gp.x;
1153  v->y_pos = gp.y;
1154  v->UpdatePosition();
1155  v->UpdateInclination(true, true);
1156  return true;
1157  }
1158 
1159  v->x_pos = gp.x;
1160  v->y_pos = gp.y;
1161  v->UpdatePosition();
1162  if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
1163  return true;
1164  }
1165 
1166  /* Get move position data for next frame.
1167  * For a drive-through road stop use 'straight road' move data.
1168  * In this case v->state is masked to give the road stop entry direction. */
1169  RoadDriveEntry rd = _road_drive_data[v->roadtype][(
1171  (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking][v->frame + 1];
1172 
1173  if (rd.x & RDE_NEXT_TILE) {
1174  TileIndex tile = v->tile + TileOffsByDiagDir((DiagDirection)(rd.x & 3));
1175  Trackdir dir;
1176 
1177  if (v->IsFrontEngine()) {
1178  /* If this is the front engine, look for the right path. */
1179  dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3));
1180  } else {
1181  dir = FollowPreviousRoadVehicle(v, prev, tile, (DiagDirection)(rd.x & 3), false);
1182  }
1183 
1184  if (dir == INVALID_TRACKDIR) {
1185  if (!v->IsFrontEngine()) error("Disconnecting road vehicle.");
1186  v->cur_speed = 0;
1187  return false;
1188  }
1189 
1190 again:
1191  uint start_frame = RVC_DEFAULT_START_FRAME;
1192  if (IsReversingRoadTrackdir(dir)) {
1193  /* When turning around we can't be overtaking. */
1194  v->overtaking = 0;
1195 
1196  /* Turning around */
1197  if (v->roadtype == ROADTYPE_TRAM) {
1198  /* Determine the road bits the tram needs to be able to turn around
1199  * using the 'big' corner loop. */
1200  RoadBits needed;
1201  switch (dir) {
1202  default: NOT_REACHED();
1203  case TRACKDIR_RVREV_NE: needed = ROAD_SW; break;
1204  case TRACKDIR_RVREV_SE: needed = ROAD_NW; break;
1205  case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
1206  case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
1207  }
1208  if ((v->Previous() != NULL && v->Previous()->tile == tile) ||
1209  (v->IsFrontEngine() && IsNormalRoadTile(tile) && !HasRoadWorks(tile) &&
1210  (needed & GetRoadBits(tile, ROADTYPE_TRAM)) != ROAD_NONE)) {
1211  /*
1212  * Taking the 'big' corner for trams only happens when:
1213  * - The previous vehicle in this (articulated) tram chain is
1214  * already on the 'next' tile, we just follow them regardless of
1215  * anything. When it is NOT on the 'next' tile, the tram started
1216  * doing a reversing turn when the piece of tram track on the next
1217  * tile did not exist yet. Do not use the big tram loop as that is
1218  * going to cause the tram to split up.
1219  * - Or the front of the tram can drive over the next tile.
1220  */
1221  } else if (!v->IsFrontEngine() || !CanBuildTramTrackOnTile(v->owner, tile, needed) || ((~needed & GetAnyRoadBits(v->tile, ROADTYPE_TRAM, false)) == ROAD_NONE)) {
1222  /*
1223  * Taking the 'small' corner for trams only happens when:
1224  * - We are not the from vehicle of an articulated tram.
1225  * - Or when the company cannot build on the next tile.
1226  *
1227  * The 'small' corner means that the vehicle is on the end of a
1228  * tram track and needs to start turning there. To do this properly
1229  * the tram needs to start at an offset in the tram turning 'code'
1230  * for 'big' corners. It furthermore does not go to the next tile,
1231  * so that needs to be fixed too.
1232  */
1233  tile = v->tile;
1234  start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
1235  } else {
1236  /* The company can build on the next tile, so wait till (s)he does. */
1237  v->cur_speed = 0;
1238  return false;
1239  }
1240  } else if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) {
1241  v->cur_speed = 0;
1242  return false;
1243  } else {
1244  tile = v->tile;
1245  }
1246  }
1247 
1248  /* Get position data for first frame on the new tile */
1249  const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(dir + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking];
1250 
1251  int x = TileX(tile) * TILE_SIZE + rdp[start_frame].x;
1252  int y = TileY(tile) * TILE_SIZE + rdp[start_frame].y;
1253 
1254  Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1255  if (v->IsFrontEngine()) {
1256  Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1257  if (u != NULL) {
1258  v->cur_speed = u->First()->cur_speed;
1259  return false;
1260  }
1261  }
1262 
1263  uint32 r = VehicleEnterTile(v, tile, x, y);
1264  if (HasBit(r, VETS_CANNOT_ENTER)) {
1265  if (!IsTileType(tile, MP_TUNNELBRIDGE)) {
1266  v->cur_speed = 0;
1267  return false;
1268  }
1269  /* Try an about turn to re-enter the previous tile */
1270  dir = _road_reverse_table[rd.x & 3];
1271  goto again;
1272  }
1273 
1274  if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) && IsTileType(v->tile, MP_STATION)) {
1275  if (IsReversingRoadTrackdir(dir) && IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1276  /* New direction is trying to turn vehicle around.
1277  * We can't turn at the exit of a road stop so wait.*/
1278  v->cur_speed = 0;
1279  return false;
1280  }
1281 
1282  /* If we are a drive through road stop and the next tile is of
1283  * the same road stop and the next tile isn't this one (i.e. we
1284  * are not reversing), then keep the reservation and state.
1285  * This way we will not be shortly unregister from the road
1286  * stop. It also makes it possible to load when on the edge of
1287  * two road stops; otherwise you could get vehicles that should
1288  * be loading but are not actually loading. */
1289  if (IsDriveThroughStopTile(v->tile) &&
1291  v->tile != tile) {
1292  /* So, keep 'our' state */
1293  dir = (Trackdir)v->state;
1294  } else if (IsRoadStop(v->tile)) {
1295  /* We're not continuing our drive through road stop, so leave. */
1297  }
1298  }
1299 
1300  if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
1301  v->tile = tile;
1302  v->state = (byte)dir;
1303  v->frame = start_frame;
1304  }
1305  if (new_dir != v->direction) {
1306  v->direction = new_dir;
1307  if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1308  }
1309  v->x_pos = x;
1310  v->y_pos = y;
1311  v->UpdatePosition();
1312  RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1313  return true;
1314  }
1315 
1316  if (rd.x & RDE_TURNED) {
1317  /* Vehicle has finished turning around, it will now head back onto the same tile */
1318  Trackdir dir;
1319  uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
1320 
1321  if (v->roadtype == ROADTYPE_TRAM && !IsRoadDepotTile(v->tile) && HasExactlyOneBit(GetAnyRoadBits(v->tile, ROADTYPE_TRAM, true))) {
1322  /*
1323  * The tram is turning around with one tram 'roadbit'. This means that
1324  * it is using the 'big' corner 'drive data'. However, to support the
1325  * trams to take a small corner, there is a 'turned' marker in the middle
1326  * of the turning 'drive data'. When the tram took the long corner, we
1327  * will still use the 'big' corner drive data, but we advance it one
1328  * frame. We furthermore set the driving direction so the turning is
1329  * going to be properly shown.
1330  */
1331  turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
1332  switch (rd.x & 0x3) {
1333  default: NOT_REACHED();
1334  case DIAGDIR_NW: dir = TRACKDIR_RVREV_SE; break;
1335  case DIAGDIR_NE: dir = TRACKDIR_RVREV_SW; break;
1336  case DIAGDIR_SE: dir = TRACKDIR_RVREV_NW; break;
1337  case DIAGDIR_SW: dir = TRACKDIR_RVREV_NE; break;
1338  }
1339  } else {
1340  if (v->IsFrontEngine()) {
1341  /* If this is the front engine, look for the right path. */
1342  dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
1343  } else {
1344  dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true);
1345  }
1346  }
1347 
1348  if (dir == INVALID_TRACKDIR) {
1349  v->cur_speed = 0;
1350  return false;
1351  }
1352 
1353  const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + dir];
1354 
1355  int x = TileX(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].x;
1356  int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
1357 
1358  Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1359  if (v->IsFrontEngine() && RoadVehFindCloseTo(v, x, y, new_dir) != NULL) return false;
1360 
1361  uint32 r = VehicleEnterTile(v, v->tile, x, y);
1362  if (HasBit(r, VETS_CANNOT_ENTER)) {
1363  v->cur_speed = 0;
1364  return false;
1365  }
1366 
1367  v->state = dir;
1368  v->frame = turn_around_start_frame;
1369 
1370  if (new_dir != v->direction) {
1371  v->direction = new_dir;
1372  if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1373  }
1374 
1375  v->x_pos = x;
1376  v->y_pos = y;
1377  v->UpdatePosition();
1378  RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1379  return true;
1380  }
1381 
1382  /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1383  * it's on a depot tile, check if it's time to activate the next vehicle in
1384  * the chain yet. */
1385  if (v->Next() != NULL && IsRoadDepotTile(v->tile)) {
1386  if (v->frame == v->gcache.cached_veh_length + RVC_DEPOT_START_FRAME) {
1387  RoadVehLeaveDepot(v->Next(), false);
1388  }
1389  }
1390 
1391  /* Calculate new position for the vehicle */
1392  int x = (v->x_pos & ~15) + (rd.x & 15);
1393  int y = (v->y_pos & ~15) + (rd.y & 15);
1394 
1395  Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1396 
1397  if (v->IsFrontEngine() && !IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1398  /* Vehicle is not in a road stop.
1399  * Check for another vehicle to overtake */
1400  RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1401 
1402  if (u != NULL) {
1403  u = u->First();
1404  /* There is a vehicle in front overtake it if possible */
1405  if (v->overtaking == 0) RoadVehCheckOvertake(v, u);
1406  if (v->overtaking == 0) v->cur_speed = u->cur_speed;
1407 
1408  /* In case an RV is stopped in a road stop, why not try to load? */
1409  if (v->cur_speed == 0 && IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1411  v->owner == GetTileOwner(v->tile) && !v->current_order.IsType(OT_LEAVESTATION) &&
1413  Station *st = Station::GetByTile(v->tile);
1414  v->last_station_visited = st->index;
1415  RoadVehArrivesAt(v, st);
1416  v->BeginLoading();
1417  }
1418  return false;
1419  }
1420  }
1421 
1422  Direction old_dir = v->direction;
1423  if (new_dir != old_dir) {
1424  v->direction = new_dir;
1425  if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1426 
1427  /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1428  * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1429  * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1430  * The short (inner) curve has 8 frames, this elongates it to 10. */
1431  v->UpdateInclination(false, true);
1432  return true;
1433  }
1434 
1435  /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1436  * if the vehicle is in a drive-through road stop and this is the destination station
1437  * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1438  * (the station test and stop type test ensure that other vehicles, using the road stop as
1439  * a through route, do not stop) */
1440  if (v->IsFrontEngine() && ((IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END) &&
1442  (IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1444  v->owner == GetTileOwner(v->tile) &&
1446  v->frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
1447 
1449  Station *st = Station::GetByTile(v->tile);
1450 
1451  /* Vehicle is at the stop position (at a bay) in a road stop.
1452  * Note, if vehicle is loading/unloading it has already been handled,
1453  * so if we get here the vehicle has just arrived or is just ready to leave. */
1454  if (!HasBit(v->state, RVS_ENTERED_STOP)) {
1455  /* Vehicle has arrived at a bay in a road stop */
1456 
1457  if (IsDriveThroughStopTile(v->tile)) {
1458  TileIndex next_tile = TILE_ADD(v->tile, TileOffsByDir(v->direction));
1459 
1460  /* Check if next inline bay is free and has compatible road. */
1461  if (RoadStop::IsDriveThroughRoadStopContinuation(v->tile, next_tile) && (GetRoadTypes(next_tile) & v->compatible_roadtypes) != 0) {
1462  v->frame++;
1463  v->x_pos = x;
1464  v->y_pos = y;
1465  v->UpdatePosition();
1466  RoadZPosAffectSpeed(v, v->UpdateInclination(true, false));
1467  return true;
1468  }
1469  }
1470 
1471  rs->SetEntranceBusy(false);
1473 
1474  v->last_station_visited = st->index;
1475 
1476  if (IsDriveThroughStopTile(v->tile) || (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == st->index)) {
1477  RoadVehArrivesAt(v, st);
1478  v->BeginLoading();
1479  return false;
1480  }
1481  } else {
1482  /* Vehicle is ready to leave a bay in a road stop */
1483  if (rs->IsEntranceBusy()) {
1484  /* Road stop entrance is busy, so wait as there is nowhere else to go */
1485  v->cur_speed = 0;
1486  return false;
1487  }
1488  if (v->current_order.IsType(OT_LEAVESTATION)) v->current_order.Free();
1489  }
1490 
1491  if (IsStandardRoadStopTile(v->tile)) rs->SetEntranceBusy(true);
1492 
1493  StartRoadVehSound(v);
1495  }
1496 
1497  /* Check tile position conditions - i.e. stop position in depot,
1498  * entry onto bridge or into tunnel */
1499  uint32 r = VehicleEnterTile(v, v->tile, x, y);
1500  if (HasBit(r, VETS_CANNOT_ENTER)) {
1501  v->cur_speed = 0;
1502  return false;
1503  }
1504 
1505  if (v->current_order.IsType(OT_LEAVESTATION) && IsDriveThroughStopTile(v->tile)) {
1506  v->current_order.Free();
1507  }
1508 
1509  /* Move to next frame unless vehicle arrived at a stop position
1510  * in a depot or entered a tunnel/bridge */
1511  if (!HasBit(r, VETS_ENTERED_WORMHOLE)) v->frame++;
1512  v->x_pos = x;
1513  v->y_pos = y;
1514  v->UpdatePosition();
1515  RoadZPosAffectSpeed(v, v->UpdateInclination(false, true));
1516  return true;
1517 }
1518 
1519 static bool RoadVehController(RoadVehicle *v)
1520 {
1521  /* decrease counters */
1522  v->current_order_time++;
1523  if (v->reverse_ctr != 0) v->reverse_ctr--;
1524 
1525  /* handle crashed */
1526  if (v->vehstatus & VS_CRASHED || RoadVehCheckTrainCrash(v)) {
1527  return RoadVehIsCrashed(v);
1528  }
1529 
1530  /* road vehicle has broken down? */
1531  if (v->HandleBreakdown()) return true;
1532  if (v->vehstatus & VS_STOPPED) return true;
1533 
1534  ProcessOrders(v);
1535  v->HandleLoading();
1536 
1537  if (v->current_order.IsType(OT_LOADING)) return true;
1538 
1539  if (v->IsInDepot() && RoadVehLeaveDepot(v, true)) return true;
1540 
1541  v->ShowVisualEffect();
1542 
1543  /* Check how far the vehicle needs to proceed */
1544  int j = v->UpdateSpeed();
1545 
1546  int adv_spd = v->GetAdvanceDistance();
1547  bool blocked = false;
1548  while (j >= adv_spd) {
1549  j -= adv_spd;
1550 
1551  RoadVehicle *u = v;
1552  for (RoadVehicle *prev = NULL; u != NULL; prev = u, u = u->Next()) {
1553  if (!IndividualRoadVehicleController(u, prev)) {
1554  blocked = true;
1555  break;
1556  }
1557  }
1558  if (blocked) break;
1559 
1560  /* Determine distance to next map position */
1561  adv_spd = v->GetAdvanceDistance();
1562 
1563  /* Test for a collision, but only if another movement will occur. */
1564  if (j >= adv_spd && RoadVehCheckTrainCrash(v)) break;
1565  }
1566 
1567  v->SetLastSpeed();
1568 
1569  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
1570  if ((u->vehstatus & VS_HIDDEN) != 0) continue;
1571 
1572  u->UpdateViewport(false, false);
1573  }
1574 
1575  /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1576  * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1577  * on next tick to discover whether it is still blocked. */
1578  if (v->progress == 0) v->progress = blocked ? adv_spd - 1 : j;
1579 
1580  return true;
1581 }
1582 
1584 {
1585  const Engine *e = this->GetEngine();
1586  if (e->u.road.running_cost_class == INVALID_PRICE) return 0;
1587 
1588  uint cost_factor = GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR, e->u.road.running_cost);
1589  if (cost_factor == 0) return 0;
1590 
1591  return GetPrice(e->u.road.running_cost_class, cost_factor, e->GetGRF());
1592 }
1593 
1595 {
1596  this->tick_counter++;
1597 
1598  if (this->IsFrontEngine()) {
1599  if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
1600  return RoadVehController(this);
1601  }
1602 
1603  return true;
1604 }
1605 
1606 static void CheckIfRoadVehNeedsService(RoadVehicle *v)
1607 {
1608  /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1609  if (Company::Get(v->owner)->settings.vehicle.servint_roadveh == 0 || !v->NeedsAutomaticServicing()) return;
1610  if (v->IsChainInDepot()) {
1612  return;
1613  }
1614 
1615  uint max_penalty;
1617  case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
1618  case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
1619  default: NOT_REACHED();
1620  }
1621 
1622  FindDepotData rfdd = FindClosestRoadDepot(v, max_penalty);
1623  /* Only go to the depot if it is not too far out of our way. */
1624  if (rfdd.best_length == UINT_MAX || rfdd.best_length > max_penalty) {
1625  if (v->current_order.IsType(OT_GOTO_DEPOT)) {
1626  /* If we were already heading for a depot but it has
1627  * suddenly moved farther away, we continue our normal
1628  * schedule? */
1629  v->current_order.MakeDummy();
1631  }
1632  return;
1633  }
1634 
1635  DepotID depot = GetDepotIndex(rfdd.tile);
1636 
1637  if (v->current_order.IsType(OT_GOTO_DEPOT) &&
1639  !Chance16(1, 20)) {
1640  return;
1641  }
1642 
1645  v->dest_tile = rfdd.tile;
1647 }
1648 
1650 {
1651  AgeVehicle(this);
1652 
1653  if (!this->IsFrontEngine()) return;
1654 
1655  if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
1656  if (this->blocked_ctr == 0) CheckVehicleBreakdown(this);
1657 
1658  CheckIfRoadVehNeedsService(this);
1659 
1660  CheckOrders(this);
1661 
1662  if (this->running_ticks == 0) return;
1663 
1665 
1666  this->profit_this_year -= cost.GetCost();
1667  this->running_ticks = 0;
1668 
1669  SubtractMoneyFromCompanyFract(this->owner, cost);
1670 
1673 }
1674 
1676 {
1677  if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
1678 
1679  if (this->IsInDepot()) {
1680  /* We'll assume the road vehicle is facing outwards */
1681  return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile));
1682  }
1683 
1684  if (IsStandardRoadStopTile(this->tile)) {
1685  /* We'll assume the road vehicle is facing outwards */
1686  return DiagDirToDiagTrackdir(GetRoadStopDir(this->tile)); // Road vehicle in a station
1687  }
1688 
1689  /* Drive through road stops / wormholes (tunnels) */
1691 
1692  /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1693  * otherwise transform it into a valid track direction */
1694  return (Trackdir)((IsReversingRoadTrackdir((Trackdir)this->state)) ? (this->state - 6) : this->state);
1695 }