simconvoi.cc 112 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/**
 * convoi_t Class for vehicle associations
 * Hansjrg Malthaner
 */

#include <stdlib.h>

#include "simdebug.h"
#include "simunits.h"
#include "simworld.h"
#include "simware.h"
#include "player/finance.h" // convert_money
#include "player/simplay.h"
#include "simconvoi.h"
#include "simhalt.h"
#include "simdepot.h"
#include "gui/simwin.h"
#include "simmenu.h"
#include "simcolor.h"
#include "simmesg.h"
#include "simintr.h"
#include "simlinemgmt.h"
#include "simline.h"
#include "freight_list_sorter.h"

#include "gui/karte.h"
#include "gui/convoi_info_t.h"
28
#include "gui/schedule_gui.h"
29 30 31 32 33 34
#include "gui/depot_frame.h"
#include "gui/messagebox.h"
#include "gui/convoi_detail_t.h"
#include "boden/grund.h"
#include "boden/wege/schiene.h"	// for railblocks

35 36
#include "descriptor/vehicle_desc.h"
#include "descriptor/roadsign_desc.h"
37

38
#include "dataobj/schedule.h"
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include "dataobj/route.h"
#include "dataobj/loadsave.h"
#include "dataobj/translator.h"
#include "dataobj/environment.h"

#include "display/viewport.h"

#include "obj/crossing.h"
#include "obj/roadsign.h"
#include "obj/wayobj.h"

#include "vehicle/simvehicle.h"
#include "vehicle/overtaker.h"

#include "utils/simrandom.h"
#include "utils/simstring.h"
#include "utils/cbuffer_t.h"


/*
 * Waiting time for loading (ms)
 * @author Hj- Malthaner
 */
#define WTT_LOADING 2000


karte_ptr_t convoi_t::welt;

/*
 * Debugging helper - translate state value to human readable name
 * @author Hj- Malthaner
 */
static const char * state_names[convoi_t::MAX_STATES] =
{
	"INITIAL",
74
	"EDIT_SCHEDULE",
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
	"ROUTING_1",
	"",
	"",
	"NO_ROUTE",
	"DRIVING",
	"LOADING",
	"WAITING_FOR_CLEARANCE",
	"WAITING_FOR_CLEARANCE_ONE_MONTH",
	"CAN_START",
	"CAN_START_ONE_MONTH",
	"SELF_DESTRUCT",	// self destruct
	"WAITING_FOR_CLEARANCE_TWO_MONTHS",
	"CAN_START_TWO_MONTHS",
	"LEAVING_DEPOT",
	"ENTERING_DEPOT"
};


/**
 * Calculates speed of slowest vehicle in the given array
 * @author Hj. Matthaner
 */
static int calc_min_top_speed(const array_tpl<vehicle_t*>& fahr, uint8 anz_vehikel)
{
	int min_top_speed = SPEED_UNLIMITED;
	for(uint8 i=0; i<anz_vehikel; i++) {
101
		min_top_speed = min(min_top_speed, kmh_to_speed( fahr[i]->get_desc()->get_topspeed() ) );
102 103 104 105 106 107 108 109 110 111
	}
	return min_top_speed;
}


void convoi_t::init(player_t *player)
{
	owner_p = player;

	is_electric = false;
112 113 114
	sum_gesamtweight = sum_weight = 0;
	sum_running_costs = sum_gear_and_power = previous_delta_v = 0;
	sum_power = 0;
115 116 117
	min_top_speed = SPEED_UNLIMITED;
	speedbonus_kmh = SPEED_UNLIMITED; // speed_to_kmh() not needed

118 119
	schedule = NULL;
	schedule_target = koord3d::invalid;
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	line = linehandle_t();

	anz_vehikel = 0;
	steps_driven = -1;
	withdraw = false;
	has_obsolete = false;
	no_load = false;
	wait_lock = 0;
	arrived_time = 0;

	jahresgewinn = 0;
	total_distance_traveled = 0;

	distance_since_last_stop = 0;
	sum_speed_limit = 0;
	maxspeed_average_count = 0;
	next_reservation_index = 0;

138
	alte_richtung = ribi_t::none;
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
	next_wolke = 0;

	state = INITIAL;

	*name_and_id = 0;
	name_offset = 0;

	freight_info_resort = true;
	freight_info_order = 0;
	loading_level = 0;
	loading_limit = 0;

	speed_limit = SPEED_UNLIMITED;
	max_record_speed = 0;
	brake_speed_soll = SPEED_UNLIMITED;
	akt_speed_soll = 0;            // target speed
	akt_speed = 0;                 // current speed
	sp_soll = 0;

	next_stop_index = 65535;

	line_update_pending = linehandle_t();

	home_depot = koord3d::invalid;

	recalc_data_front = true;
	recalc_data = true;
}


169
convoi_t::convoi_t(loadsave_t* file) : fahr(default_vehicle_length, NULL)
170 171 172 173 174 175 176
{
	self = convoihandle_t();
	init(0);
	rdwr(file);
}


177
convoi_t::convoi_t(player_t* player_) : fahr(default_vehicle_length, NULL)
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
{
	self = convoihandle_t(this);
	player_->book_convoi_number(1);
	init(player_);
	set_name( "Unnamed" );
	welt->add_convoi( self );
	init_financial_history();
}


convoi_t::~convoi_t()
{
	owner_p->book_convoi_number( -1);

	assert(self.is_bound());
	assert(anz_vehikel==0);

	// close windows
	destroy_win( magic_convoi_info+self.get_id() );
	destroy_win( magic_convoi_detail+self.get_id() );

DBG_MESSAGE("convoi_t::~convoi_t()", "destroying %d, %p", self.get_id(), this);
	// stop following
	if(welt->get_viewport()->get_follow_convoi()==self) {
		welt->get_viewport()->set_follow_convoi( convoihandle_t() );
	}

205
	welt->sync.remove( this );
206 207 208 209 210 211 212 213
	welt->rem_convoi( self );

	// Knightly : if lineless convoy -> unregister from stops
	if(  !line.is_bound()  ) {
		unregister_stops();
	}

	// force asynchronous recalculation
214 215 216
	if(schedule) {
		if(!schedule->is_editing_finished()) {
			destroy_win((ptrdiff_t)schedule);
217
		}
218
		if (!schedule->empty() && !line.is_bound()) {
219 220
			welt->set_schedule_counter();
		}
221
		delete schedule;
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
	}

	// @author hsiegeln - deregister from line (again) ...
	unset_line();

	self.detach();
}


// waypoint: no stop, resp. for airplanes in air (i.e. no air strip below)
bool convoi_t::is_waypoint( koord3d ziel ) const
{
	if(  fahr[0]->get_waytype() == air_wt  ) {
		// separate logic for airplanes, since the can have waypoints over stops etc.
		grund_t *gr = welt->lookup_kartenboden(ziel.get_2d());
		if(  gr == NULL  ||  gr->get_weg(air_wt) == NULL  ) {
			// during flight always a waypoint
			return true;
		}
		else if(  gr->get_depot()  ) {
			// but a depot is not a waypoint
			return false;
		}
		// so we are on a taxiway/runway here ...
	}
	return !haltestelle_t::get_halt(ziel,get_owner()).is_bound();
}


/**
 * unreserves the whole remaining route
 */
void convoi_t::unreserve_route()
{
	// need a route, vehicles, and vehicles must belong to this convoi
	// (otherwise crash during loading when fahr[0]->convoi is not initialized yet
	if(  !route.empty()  &&  anz_vehikel>0  &&  fahr[0]->get_convoi() == this  ) {
		rail_vehicle_t* lok = dynamic_cast<rail_vehicle_t*>(fahr[0]);
		if (lok) {
			// free all reserved blocks
			uint16 dummy;
			lok->block_reserver(get_route(), back()->get_route_index(), dummy, dummy,  100000, false, true);
		}
	}
}


/**
270
 * reserves route until next_reservation_index
271 272 273 274 275
 */
void convoi_t::reserve_route()
{
	if(  !route.empty()  &&  anz_vehikel>0  &&  (is_waiting()  ||  state==DRIVING  ||  state==LEAVING_DEPOT)  ) {
		for(  int idx = back()->get_route_index();  idx < next_reservation_index  /*&&  idx < route.get_count()*/;  idx++  ) {
276
			if(  grund_t *gr = welt->lookup( route.at(idx) )  ) {
277
				if(  schiene_t *sch = (schiene_t *)gr->get_weg( front()->get_waytype() )  ) {
278
					sch->reserve( self, ribi_type( route.at(max(1u,idx)-1u), route.at(min(route.get_count()-1u,idx+1u)) ) );
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
				}
			}
		}
	}
}

/**
 * Sets route_index of all vehicles to startindex.
 * Puts all vehicles on tile at this position in the route.
 * Convoy stills needs to be pushed that the convoy is right on track.
 * @returns length of convoy minus last vehicle
 */
uint32 convoi_t::move_to(uint16 const start_index)
{
	steps_driven = -1;
294
	koord3d k = route.at(start_index);
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
	grund_t* gr = welt->lookup(k);

	uint32 train_length = 0;
	for (unsigned i = 0; i != anz_vehikel; ++i) {
		vehicle_t& v = *fahr[i];

		if(  grund_t const* gr = welt->lookup(v.get_pos())  ) {
			v.mark_image_dirty(v.get_image(), 0);
			v.leave_tile();
			// maybe unreserve this
			if(  schiene_t* const rails = obj_cast<schiene_t>(gr->get_weg(v.get_waytype()))  ) {
				rails->unreserve(&v);
			}
		}
		// propagate new index to vehicle, will set all movement related variables, in particular pos
		v.initialise_journey(start_index, true);
		// now put vehicle on the tile
		if (gr) {
			v.enter_tile(gr);
		}

		if (i != anz_vehikel - 1U) {
317
			train_length += v.get_desc()->get_length();
318 319 320 321 322 323 324 325
		}
	}
	return train_length;
}


void convoi_t::finish_rd()
{
326
	if(schedule==NULL) {
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
		if(  state!=INITIAL  ) {
			grund_t *gr = welt->lookup(home_depot);
			if(gr  &&  gr->get_depot()) {
				dbg->warning( "convoi_t::finish_rd()","No schedule during loading convoi %i: State will be initial!", self.get_id() );
				for( uint8 i=0;  i<anz_vehikel;  i++ ) {
					fahr[i]->set_pos(home_depot);
				}
				state = INITIAL;
			}
			else {
				dbg->error( "convoi_t::finish_rd()","No schedule during loading convoi %i: Convoi will be destroyed!", self.get_id() );
				for( uint8 i=0;  i<anz_vehikel;  i++ ) {
					fahr[i]->set_pos(koord3d::invalid);
				}
				destroy();
				return;
			}
		}
		// anyway reassign convoi pointer ...
		for( uint8 i=0;  i<anz_vehikel;  i++ ) {
			vehicle_t* v = fahr[i];
			v->set_convoi(this);
			if(  state!=INITIAL  &&  welt->lookup(v->get_pos())  ) {
				// mark vehicle as used
				v->set_driven();
			}
		}
		return;
	}
	else {
		// restore next schedule target for non-stop waypoint handling
358
		const koord3d ziel = schedule->get_current_entry().pos;
359
		if(  anz_vehikel>0  &&  is_waypoint(ziel)  ) {
360
			schedule_target = ziel;
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
		}
	}

	bool realing_position = false;
	if(  anz_vehikel>0  ) {
DBG_MESSAGE("convoi_t::finish_rd()","state=%s, next_stop_index=%d", state_names[state], next_stop_index );
		// only realign convois not leaving depot to avoid jumps through signals
		if(  steps_driven!=-1  ) {
			for( uint8 i=0;  i<anz_vehikel;  i++ ) {
				vehicle_t* v = fahr[i];
				v->set_leading( i==0 );
				v->set_last( i+1==anz_vehikel );
				v->calc_height();
				// this sets the convoi and will renew the block reservation, if needed!
				v->set_convoi(this);
			}
		}
		else {
			// test also for realignment
			sint16 step_pos = 0;
			koord3d drive_pos;
			uint8 const diagonal_vehicle_steps_per_tile = (uint8)(130560U / welt->get_settings().get_pak_diagonal_multiplier());
			for( uint8 i=0;  i<anz_vehikel;  i++ ) {
				vehicle_t* v = fahr[i];
				v->set_leading( i==0 );
				v->set_last( i+1==anz_vehikel );
				v->calc_height();
				// this sets the convoi and will renew the block reservation, if needed!
				v->set_convoi(this);

				// wrong alignment here => must relocate
				if(v->need_realignment()) {
					// diagonal => convoi must restart
394
					realing_position |= ribi_t::is_bend(v->get_direction())  &&  (state==DRIVING  ||  is_waiting());
395 396 397 398 399 400 401 402 403 404 405 406 407 408
				}
				// if version is 99.17 or lower, some convois are broken, i.e. had too large gaps between vehicles
				if(  !realing_position  &&  state!=INITIAL  &&  state!=LEAVING_DEPOT  ) {
					if(  i==0  ) {
						step_pos = v->get_steps();
					}
					else {
						if(  drive_pos!=v->get_pos()  ) {
							// with long vehicles on diagonals, vehicles need not to be on consecutive tiles
							// do some guessing here
							uint32 dist = koord_distance(drive_pos, v->get_pos());
							if (dist>1) {
								step_pos += (dist-1) * diagonal_vehicle_steps_per_tile;
							}
409
							step_pos += ribi_t::is_bend(v->get_direction()) ? diagonal_vehicle_steps_per_tile : VEHICLE_STEPS_PER_TILE;
410
						}
411
						dbg->message("convoi_t::finish_rd()", "v: pos(%s) steps(%d) len=%d ribi=%d prev (%s) step(%d)", v->get_pos().get_str(), v->get_steps(), v->get_desc()->get_length()*16, v->get_direction(),  drive_pos.get_2d().get_str(), step_pos);
412 413 414 415 416 417
						if(  abs( v->get_steps() - step_pos )>15  ) {
							// not where it should be => realign
							realing_position = true;
							dbg->warning( "convoi_t::finish_rd()", "convoi (%s) is broken => realign", get_name() );
						}
					}
418
					step_pos -= v->get_desc()->get_length_in_steps();
419 420 421 422 423 424 425 426 427 428 429 430
					drive_pos = v->get_pos();
				}
			}
		}
DBG_MESSAGE("convoi_t::finish_rd()","next_stop_index=%d", next_stop_index );

		linehandle_t new_line  = line;
		if(  !new_line.is_bound()  ) {
			// if there is a line with id=0 in the savegame try to assign cnv to this line
			new_line = get_owner()->simlinemgmt.get_line_with_id_zero();
		}
		if(  new_line.is_bound()  ) {
431
			if (  !schedule->matches( welt, new_line->get_schedule() )  ) {
432 433
				// 101 version produced broken line ids => we have to find our line the hard way ...
				vector_tpl<linehandle_t> lines;
434
				get_owner()->simlinemgmt.get_lines(schedule->get_type(), &lines);
435 436
				new_line = linehandle_t();
				FOR(vector_tpl<linehandle_t>, const l, lines) {
437
					if(  schedule->matches( welt, l->get_schedule() )  ) {
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
						// if a line is assigned, set line!
						new_line = l;
						break;
					}
				}
			}
			// now the line should match our schedule or else ...
			if(new_line.is_bound()) {
				line = new_line;
				line->add_convoy(self);
				DBG_DEBUG("convoi_t::finish_rd()","%s registers for %d", name_and_id, line.get_id());
			}
			else {
				line = linehandle_t();
			}
		}
	}
	else {
		// no vehicles in this convoi?!?
		dbg->error( "convoi_t::finish_rd()","No vehicles in Convoi %i: will be destroyed!", self.get_id() );
		destroy();
		return;
	}
	// put convoi again right on track?
	if(realing_position  &&  anz_vehikel>1) {
		// display just a warning
		dbg->warning("convoi_t::finish_rd()","cnv %i is currently too long.",self.get_id());

		if (route.empty()) {
			// realigning needs a route
			state = NO_ROUTE;
			owner_p->report_vehicle_problem( self, koord3d::invalid );
			dbg->error( "convoi_t::finish_rd()", "No valid route, but needs realignment at (%s)!", fahr[0]->get_pos().get_str() );
		}
		else {
			// since start may have been changed
			uint16 start_index = max(1,fahr[anz_vehikel-1]->get_route_index())-1;
475 476 477 478
			if (start_index > route.get_count()) {
				dbg->error( "convoi_t::finish_rd()", "Routeindex of last vehicle of (%s) too large!", get_name() );
				start_index = 0;
			}
479 480 481 482 483 484 485 486 487 488 489

			uint32 train_length = move_to(start_index) + 1;
			const koord3d last_start = fahr[0]->get_pos();

			// now advance all convoi until it is completely on the track
			fahr[0]->set_leading(false); // switches off signal checks ...
			for(unsigned i=0; i<anz_vehikel; i++) {
				vehicle_t* v = fahr[i];

				v->get_smoke(false);
				fahr[i]->do_drive( (VEHICLE_STEPS_PER_CARUNIT*train_length)<<YARDS_PER_VEHICLE_STEP_SHIFT );
490
				train_length -= v->get_desc()->get_length();
491 492 493 494 495 496
				v->get_smoke(true);

				// eventually reserve this again
				grund_t *gr=welt->lookup(v->get_pos());
				// airplanes may have no ground ...
				if (schiene_t* const sch0 = obj_cast<schiene_t>(gr->get_weg(fahr[i]->get_waytype()))) {
497
					sch0->reserve(self,ribi_t::none);
498 499 500
				}
			}
			fahr[0]->set_leading(true);
501
			if(  state != INITIAL  &&  state != EDIT_SCHEDULE  &&  fahr[0]->get_pos() != last_start  ) {
502 503 504 505 506 507 508 509 510
				state = WAITING_FOR_CLEARANCE;
			}
		}
	}
	if(  state==LOADING  ) {
		// the fully the shorter => register again as older convoi
		wait_lock = 2000-loading_level*20;
	}
	// when saving with open window, this can happen
511
	if(  state==EDIT_SCHEDULE  ) {
512 513 514
		if (env_t::networkmode) {
			wait_lock = 30000; // 60s to drive on, if the client in question had left
		}
515
		schedule->finish_editing();
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
	}
	// remove wrong freight
	check_freight();
	// some convois had wrong old direction in them
	if(  state<DRIVING  ||  state==LOADING  ) {
		alte_richtung = fahr[0]->get_direction();
	}
	// Knightly : if lineless convoy -> register itself with stops
	if(  !line.is_bound()  ) {
		register_stops();
	}

	calc_speedbonus_kmh();
}


// since now convoi states go via tool_t
void convoi_t::call_convoi_tool( const char function, const char *extra ) const
{
	tool_t *tmp_tool = create_tool( TOOL_CHANGE_CONVOI | SIMPLE_TOOL );
	cbuffer_t param;
	param.printf("%c,%u", function, self.get_id());
	if(  extra  &&  *extra  ) {
		param.printf(",%s", extra);
	}
	tmp_tool->set_default_param(param);
	welt->set_tool( tmp_tool, get_owner() );
	// since init always returns false, it is safe to delete immediately
	delete tmp_tool;
}


void convoi_t::rotate90( const sint16 y_size )
{
	record_pos.rotate90( y_size );
	home_depot.rotate90( y_size );
	route.rotate90( y_size );
553 554
	if(  schedule_target!=koord3d::invalid  ) {
		schedule_target.rotate90( y_size );
555
	}
556 557
	if(schedule) {
		schedule->rotate90( y_size );
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
	}
	for(  int i=0;  i<anz_vehikel;  i++  ) {
		fahr[i]->rotate90_freight_destinations( y_size );
	}
	// eventually correct freight destinations (and remove all stale freight)
	check_freight();
}


/**
 * Return the convoi position.
 * @return Convoi position
 * @author Hj. Malthaner
 */
koord3d convoi_t::get_pos() const
{
	if(anz_vehikel > 0 && fahr[0]) {
		return state==INITIAL ? home_depot : fahr[0]->get_pos();
	}
	else {
		return koord3d::invalid;
	}
}


/**
 * Sets the name. Creates a copy of name.
 * @author Hj. Malthaner
 */
void convoi_t::set_name(const char *name, bool with_new_id)
{
	if(  with_new_id  ) {
		char buf[128];
		name_offset = sprintf(buf,"(%i) ",self.get_id() );
		tstrncpy(buf + name_offset, translator::translate(name, welt->get_settings().get_name_language_id()), lengthof(buf) - name_offset);
		tstrncpy(name_and_id, buf, lengthof(name_and_id));
	}
	else {
		char buf[128];
		// check if there is a id in the name string
		name_offset = sprintf(buf,"(%i) ",self.get_id() );
		if(  strlen(name) < name_offset  ||  strncmp(buf,name,name_offset)!=0) {
			name_offset = 0;
		}
		tstrncpy(buf+name_offset, name+name_offset, sizeof(buf)-name_offset);
		tstrncpy(name_and_id, buf, lengthof(name_and_id));
	}
	// now tell the windows that we were renamed
	convoi_detail_t *detail = dynamic_cast<convoi_detail_t*>(win_get_magic( magic_convoi_detail+self.get_id()));
	if (detail) {
		detail->update_data();
	}
	convoi_info_t *info = dynamic_cast<convoi_info_t*>(win_get_magic( magic_convoi_info+self.get_id()));
	if (info) {
		info->update_data();
	}
	if(  in_depot()  ) {
		const grund_t *const ground = welt->lookup( get_home_depot() );
		if(  ground  ) {
			const depot_t *const depot = ground->get_depot();
			if(  depot  ) {
				depot_frame_t *const frame = dynamic_cast<depot_frame_t *>( win_get_magic( (ptrdiff_t)depot ) );
				if(  frame  ) {
					frame->update_data();
				}
			}
		}
	}
}


// length of convoi (16 is one tile)
uint32 convoi_t::get_length() const
{
	uint32 len = 0;
	for( uint8 i=0; i<anz_vehikel; i++ ) {
634
		len += fahr[i]->get_desc()->get_length();
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
	}
	return len;
}


/**
 * convoi add their running cost for traveling one tile
 * @author Hj. Malthaner
 */
void convoi_t::add_running_cost( const weg_t *weg )
{
	jahresgewinn += sum_running_costs;

	if(  weg  &&  weg->get_owner()!=get_owner()  &&  weg->get_owner()!=NULL  ) {
		// running on non-public way costs toll (since running costs are positive => invert)
		sint32 toll = -(sum_running_costs*welt->get_settings().get_way_toll_runningcost_percentage())/100l;
		if(  welt->get_settings().get_way_toll_waycost_percentage()  ) {
			if(  weg->is_electrified()  &&  needs_electrification()  ) {
				// toll for using electricity
				grund_t *gr = welt->lookup(weg->get_pos());
				for(  int i=1;  i<gr->get_top();  i++  ) {
					obj_t *d=gr->obj_bei(i);
					if(  wayobj_t const* const wo = obj_cast<wayobj_t>(d)  )  {
						if(  wo->get_waytype()==weg->get_waytype()  ) {
659
							toll += (wo->get_desc()->get_maintenance()*welt->get_settings().get_way_toll_waycost_percentage())/100l;
660 661 662 663 664 665
							break;
						}
					}
				}
			}
			// now add normal way toll be maintenance
666
			toll += (weg->get_desc()->get_maintenance()*welt->get_settings().get_way_toll_waycost_percentage())/100l;
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
		}
		weg->get_owner()->book_toll_received( toll, get_schedule()->get_waytype() );
		get_owner()->book_toll_paid(         -toll, get_schedule()->get_waytype() );
		book( -toll, CONVOI_WAYTOLL);
		book( -toll, CONVOI_PROFIT);
	}
	get_owner()->book_running_costs( sum_running_costs, get_schedule()->get_waytype());

	book( sum_running_costs, CONVOI_OPERATIONS );
	book( sum_running_costs, CONVOI_PROFIT );

	total_distance_traveled ++;
	distance_since_last_stop++;

	sum_speed_limit += speed_to_kmh( min( min_top_speed, speed_limit ));
	book( 1, CONVOI_DISTANCE );
}


/**
 * Returns residual power given power, weight, and current speed.
 * @param speed (in internal speed unit)
689
 * @param total_power sum of power times gear (see calculation of sum_gear_and_power)
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
 * @param friction_weight weight including friction of the convoy
 * @param total_weight weight of the convoy
 * @returns residual power
 */
static inline sint32 res_power(sint64 speed, sint32 total_power, sint64 friction_weight, sint64 total_weight)
{
	sint32 res = total_power - (sint32)( ( (sint64)speed * ( (friction_weight * (sint64)speed ) / 3125ll + 1ll) ) / 2048ll + (total_weight * 64ll) / 1000ll);
	return res;
}

/* Calculates (and sets) new akt_speed
 * needed for driving, entering and leaving a depot)
 */
void convoi_t::calc_acceleration(uint32 delta_t)
{
	if(  !recalc_data  &&  !recalc_speed_limit  &&  !recalc_data_front  &&  (
706 707
		(sum_friction_weight == sum_gesamtweight  &&  akt_speed_soll <= akt_speed  &&  akt_speed_soll+24 >= akt_speed)  ||
		(sum_friction_weight > sum_gesamtweight  &&  akt_speed_soll == akt_speed)  )
708 709 710 711 712 713 714 715 716 717 718 719 720
		) {
		// at max speed => go with max speed and finish calculation here
		// at slopes/curves, only do this if there is absolutely now change
		akt_speed = akt_speed_soll;
		return;
	}

	// Dwachs: only compute this if a vehicle in the convoi hopped
	if(  recalc_data  ||  recalc_speed_limit  ) {
		// calculate total friction and lowest speed limit
		const vehicle_t* v = front();
		speed_limit = min( min_top_speed, v->get_speed_limit() );
		if (recalc_data) {
721 722
			sum_gesamtweight   = v->get_total_weight();
			sum_friction_weight = v->get_frictionfactor() * sum_gesamtweight;
723 724 725 726 727 728 729 730 731
		}

		for(  unsigned i=1; i<anz_vehikel; i++  ) {
			const vehicle_t* v = fahr[i];
			speed_limit = min( speed_limit, v->get_speed_limit() );

			if (recalc_data) {
				int total_vehicle_weight = v->get_total_weight();
				sum_friction_weight += v->get_frictionfactor() * total_vehicle_weight;
732
				sum_gesamtweight += total_vehicle_weight;
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
			}
		}
		recalc_data = recalc_speed_limit = false;
		akt_speed_soll = min( speed_limit, brake_speed_soll );
	}

	if(  recalc_data_front  ) {
		// brake at the end of stations/in front of signals and crossings
		const uint32 tiles_left = 1 + get_next_stop_index() - front()->get_route_index();
		brake_speed_soll = SPEED_UNLIMITED;
		if(  tiles_left < 4  ) {
			static sint32 brake_speed_countdown[4] = {
				kmh_to_speed(25),
				kmh_to_speed(50),
				kmh_to_speed(100),
				kmh_to_speed(200)
			};
			brake_speed_soll = brake_speed_countdown[tiles_left];
		}
		akt_speed_soll = min( speed_limit, brake_speed_soll );
		recalc_data_front = false;
	}

	// Prissi: more pleasant and a little more "physical" model *

	// try to simulate quadratic friction
759
	if(sum_gesamtweight != 0) {
760 761 762 763 764 765 766 767 768 769
		/*
			* The parameter consist of two parts (optimized for good looking):
			*  - every vehicle in a convoi has a the friction of its weight
			*  - the dynamic friction is calculated that way, that v^2*weight*frictionfactor = 200 kW
			* => heavier loaded and faster traveling => less power for acceleration is available!
			* since delta_t can have any value, we have to scale the step size by this value.
			* however, there is a quadratic friction term => if delta_t is too large the calculation may get weird results
			* @author prissi
			*/

770
		/* but for integer, we have to use the order below and calculate actually 64*deccel, like the sum_gear_and_power
771 772
			* since akt_speed=10/128 km/h and we want 64*200kW=(100km/h)^2*100t, we must multiply by (128*2)/100
			* But since the acceleration was too fast, we just decelerate 4x more => >>6 instead >>8 */
773 774 775
		//sint32 deccel = ( ( (akt_speed*sum_friction_weight)>>6 )*(akt_speed>>2) ) / 25 + (sum_gesamtweight*64);	// this order is needed to prevent overflows!
		//sint32 deccel = (sint32)( ( (sint64)akt_speed * (sint64)sum_friction_weight * (sint64)akt_speed ) / (25ll*256ll) + sum_gesamtweight * 64ll) / 1000ll; // intermediate still overflows so sint64
		//sint32 deccel = (sint32)( ( (sint64)akt_speed * ( (sum_friction_weight * (sint64)akt_speed ) / 3125ll + 1ll) ) / 2048ll + (sum_gesamtweight * 64ll) / 1000ll);
776 777 778

		// prissi: integer sucks with planes => using floats ...
		// turfit: result can overflow sint32 and double so onto sint64. planes ok.
779
		//sint32 delta_v =  (sint32)( ( (double)( (akt_speed>akt_speed_soll?0l:sum_gear_and_power) - deccel)*(double)delta_t)/(double)sum_gesamtweight);
780

781
		sint64 residual_power = res_power(akt_speed, akt_speed>akt_speed_soll? 0l : sum_gear_and_power, sum_friction_weight, sum_gesamtweight);
782 783

		// we normalize delta_t to 1/64th and check for speed limit */
784 785
		//sint32 delta_v = ( ( (akt_speed>akt_speed_soll?0l:sum_gear_and_power) - deccel) * delta_t)/sum_gesamtweight;
		sint64 delta_v = ( residual_power * (sint64)delta_t * 1000ll) / (sint64)sum_gesamtweight;
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866

		// we need more accurate arithmetic, so we store the previous value
		delta_v += previous_delta_v;
		previous_delta_v = (sint32)(delta_v & 0x00000FFFll);
		// and finally calculate new speed
		akt_speed = max(akt_speed_soll>>4, akt_speed+(sint32)(delta_v>>12l) );
	}
	else {
		// very old vehicle ...
		akt_speed += 16;
	}

	// obey speed maximum with additional const brake ...
	if(akt_speed > akt_speed_soll) {
		if (akt_speed > akt_speed_soll + 24) {
			akt_speed -= 24;
			if(akt_speed > akt_speed_soll+kmh_to_speed(20)) {
				akt_speed = akt_speed_soll+kmh_to_speed(20);
			}
		}
		else {
			akt_speed = akt_speed_soll;
		}
	}

	// new record?
	if(akt_speed > max_record_speed) {
		max_record_speed = akt_speed;
		record_pos = fahr[0]->get_pos().get_2d();
	}
}


/**
 * Calculates maximal possible speed.
 * Uses iterative technique to take care of integer arithmetic.
 */
sint32 convoi_t::calc_max_speed(uint64 total_power, uint64 total_weight, sint32 speed_limit)
{
	// precision is 0.5 km/h
	const sint32 tol = kmh_to_speed(1)/2;
	// bisection to find max speed
	sint32 pl,pr,pm;
	sint64 sl,sr,sm;

	// test speed_limit
	sr = speed_limit;
	pr = res_power(sr, (sint32)total_power, total_weight, total_weight);
	if (pr >= 0) {
		return (sint32)sr; // convoy can travel at speed given by speed_limit
	}
	sl = 1;
	pl = res_power(sl, (sint32)total_power, total_weight, total_weight);
	if (pl <= 0) {
		return 0; // no power to move at all
	}

	// bisection algorithm to find speed for which residual power is zero
	while (sr - sl > tol) {
		sm = (sl + sr)/2;
		if (sm == sl) break;

		pm = res_power(sm, (sint32)total_power, total_weight, total_weight);

		if (((sint64)pl)*pm <= 0) {
			pr = pm;
			sr = sm;
		}
		else {
			pl = pm;
			sl = sm;
		}
	}
	return (sint32)sl;
}


int convoi_t::get_vehicle_at_length(uint16 length)
{
	int current_length = 0;
	for( int i=0;  i<anz_vehikel;  i++  ) {
867
		current_length += fahr[i]->get_desc()->get_length();
868 869 870 871 872 873 874 875 876
		if(length<current_length) {
			return i;
		}
	}
	return anz_vehikel;
}


// moves all vehicles of a convoi
877
sync_result convoi_t::sync_step(uint32 delta_t)
878 879 880 881
{
	// still have to wait before next action?
	wait_lock -= delta_t;
	if(wait_lock > 0) {
882
		return SYNC_OK;
883 884 885 886 887
	}
	wait_lock = 0;

	switch(state) {
		case INITIAL:
888 889
			// in depot, should not be in sync list, remove
			return SYNC_REMOVE;
890

891
		case EDIT_SCHEDULE:
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
		case ROUTING_1:
		case DUMMY4:
		case DUMMY5:
		case NO_ROUTE:
		case CAN_START:
		case CAN_START_ONE_MONTH:
		case CAN_START_TWO_MONTHS:
			// Hajo: this is an async task, see step()
			break;

		case ENTERING_DEPOT:
			break;

		case LEAVING_DEPOT:
			{
				// ok, so we will accelerate
				akt_speed_soll = max( akt_speed_soll, kmh_to_speed(30) );
				calc_acceleration(delta_t);
				sp_soll += (akt_speed*delta_t);

				// now actually move the units
				while(sp_soll>>12) {
					// Attempt to move one step.
					uint32 sp_hat = fahr[0]->do_drive(1<<YARDS_PER_VEHICLE_STEP_SHIFT);
					int v_nr = get_vehicle_at_length((++steps_driven)>>4);
					// stop when depot reached
918 919 920 921
					if (state==INITIAL) {
						return SYNC_REMOVE;
					}
					if (state==ROUTING_1) {
922 923 924 925 926 927
						break;
					}
					// until all are moving or something went wrong (sp_hat==0)
					if(sp_hat==0  ||  v_nr==anz_vehikel) {
						steps_driven = -1;
						state = DRIVING;
928
						return SYNC_OK;
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
					}
					// now only the right numbers
					for(int i=1; i<=v_nr; i++) {
						fahr[i]->do_drive(sp_hat);
					}
					sp_soll -= sp_hat;
				}
				// smoke for the engines
				next_wolke += delta_t;
				if(next_wolke>500) {
					next_wolke = 0;
					for(int i=0;  i<anz_vehikel;  i++  ) {
						fahr[i]->make_smoke();
					}
				}
			}
			break;	// LEAVING_DEPOT

		case DRIVING:
			{
				calc_acceleration(delta_t);

				// now actually move the units
				sp_soll += (akt_speed*delta_t);
				uint32 sp_hat = fahr[0]->do_drive(sp_soll);
				// stop when depot reached ...
				if(state==INITIAL) {
956
					return SYNC_REMOVE;
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
				}
				// now move the rest (so all vehikel are moving synchronously)
				for(unsigned i=1; i<anz_vehikel; i++) {
					fahr[i]->do_drive(sp_hat);
				}
				// maybe we have been stopped be something => avoid wide jumps
				sp_soll = (sp_soll-sp_hat) & 0x0FFF;

				// smoke for the engines
				next_wolke += delta_t;
				if(next_wolke>500) {
					next_wolke = 0;
					for(int i=0;  i<anz_vehikel;  i++  ) {
						fahr[i]->make_smoke();
					}
				}
			}
			break;	// DRIVING

		case LOADING:
			// Hajo: loading is an async task, see laden()
			break;

		case WAITING_FOR_CLEARANCE:
		case WAITING_FOR_CLEARANCE_ONE_MONTH:
		case WAITING_FOR_CLEARANCE_TWO_MONTHS:
			// Hajo: waiting is asynchronous => fixed waiting order and route search
			break;

		case SELF_DESTRUCT:
			// see step, since destruction during a screen update may give strange effects
			break;

		default:
			dbg->fatal("convoi_t::sync_step()", "Wrong state %d!\n", state);
			break;
	}

995
	return SYNC_OK;
996 997 998 999 1000 1001 1002 1003 1004 1005
}


/**
 * Berechne route von Start- zu Zielkoordinate
 * @author Hanjsrg Malthaner
 */
bool convoi_t::drive_to()
{
	if(  anz_vehikel>0  ) {
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

		// unreserve all tiles that are covered by the train but do not contain one of the wagons,
		// otherwise repositioning of the train drive_to may lead to stray reserved tiles
		if (dynamic_cast<rail_vehicle_t*>(fahr[0])!=NULL  &&  anz_vehikel > 1) {
			// route-index points to next position in route
			// it is completely off when convoi leaves depot
			uint16 index0 = min(fahr[0]->get_route_index()-1, route.get_count());
			for(uint8 i=1; i<anz_vehikel; i++) {
				uint16 index1 = fahr[i]->get_route_index();
				for(uint16 j = index1; j<index0; j++) {
					// unreserve track on tiles between wagons
					grund_t *gr = welt->lookup(route.at(j));
					if (schiene_t *track = (schiene_t *)gr->get_weg( front()->get_waytype() ) ) {
						track->unreserve(self);
					}
				}
				index0 = min(index1-1, route.get_count());
			}
		}

1026
		koord3d start = fahr[0]->get_pos();
1027
		koord3d ziel = schedule->get_current_entry().pos;
1028 1029 1030 1031 1032 1033

		// avoid stopping mid-halt
		if(  start==ziel  ) {
			halthandle_t halt = haltestelle_t::get_halt(ziel,get_owner());
			if(  halt.is_bound()  &&  route.is_contained(start)  ) {
				for(  uint32 i=route.index_of(start);  i<route.get_count();  i++  ) {
1034
					grund_t *gr = welt->lookup(route.at(i));
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
					if(  gr  && gr->get_halt()==halt  ) {
						ziel = gr->get_pos();
					}
					else {
						break;
					}
				}
			}
		}

		if(  !fahr[0]->calc_route( start, ziel, speed_to_kmh(min_top_speed), &route )  ) {
			if(  state != NO_ROUTE  ) {
				state = NO_ROUTE;
				get_owner()->report_vehicle_problem( self, ziel );
			}
			// wait 25s before next attempt
			wait_lock = 25000;
		}
		else {
			bool route_ok = true;
1055
			const uint8 current_stop = schedule->get_current_stop();
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
			if(  fahr[0]->get_waytype() != water_wt  ) {
				air_vehicle_t *const plane = dynamic_cast<air_vehicle_t *>(fahr[0]);
				uint32 takeoff = 0, search = 0, landing = 0;
				air_vehicle_t::flight_state plane_state = air_vehicle_t::taxiing;
				if(  plane  ) {
					// due to the complex state system of aircrafts, we have to save index and state
					plane->get_event_index( plane_state, takeoff, search, landing );
				}

				// set next schedule target position if next is a waypoint
				if(  is_waypoint(ziel)  ) {
1067
					schedule_target = ziel;
1068 1069 1070 1071 1072
				}

				// continue route search until the destination is a station
				while(  is_waypoint(ziel)  ) {
					start = ziel;
1073 1074
					schedule->advance();
					ziel = schedule->get_current_entry().pos;
1075

1076
					if(  schedule->get_current_stop() == current_stop  ) {
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
						// looped around without finding a halt => entire schedule is waypoints.
						break;
					}

					route_t next_segment;
					if(  !fahr[0]->calc_route( start, ziel, speed_to_kmh(min_top_speed), &next_segment )  ) {
						// do we still have a valid route to proceed => then go until there
						if(  route.get_count()>1  ) {
							break;
						}
						// we are stuck on our first routing attempt => give up
						if(  state != NO_ROUTE  ) {
							state = NO_ROUTE;
							get_owner()->report_vehicle_problem( self, ziel );
						}
						// wait 25s before next attempt
						wait_lock = 25000;
						route_ok = false;
						break;
					}
					else {
						bool looped = false;
						if(  fahr[0]->get_waytype() != air_wt  ) {
							 // check if the route circles back on itself (only check the first tile, should be enough)
1101
							looped = route.is_contained(next_segment.at(1));
1102 1103 1104
#if 0
							// this will forbid an eight figure, which might be clever to avoid a problem of reserving one own track
							for(  unsigned i = 1;  i<next_segment.get_count();  i++  ) {
1105
								if(  route.is_contained(next_segment.at(i))  ) {
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
									looped = true;
									break;
								}
							}
#endif
						}

						if(  looped  ) {
							// proceed upto the waypoint before the loop. Will pause there for a new route search.
							break;
						}
						else {
							uint32 count_offset = route.get_count()-1;
							route.append( &next_segment);
							if(  plane  ) {
								// maybe we need to restore index
								air_vehicle_t::flight_state dummy1;
								uint32 new_takeoff, new_search, new_landing;
								plane->get_event_index( dummy1, new_takeoff, new_search, new_landing );
								if(  takeoff == 0x7FFFFFFF  &&  new_takeoff != 0x7FFFFFFF  ) {
									takeoff = new_takeoff + count_offset;
								}
								if(  landing == 0x7FFFFFFF  &&  new_landing != 0x7FFFFFFF  ) {
									landing = new_landing + count_offset;
								}
								if(  search == 0x7FFFFFFF  &&  new_search != 0x7FFFFFFF ) {
									search = new_search + count_offset;
								}
							}
						}
					}
				}

				if(  plane  ) {
					// due to the complex state system of aircrafts, we have to restore index and state
					plane->set_event_index( plane_state, takeoff, search, landing );
				}
			}

1145
			schedule->set_current_stop(current_stop);
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
			if(  route_ok  ) {
				vorfahren();
				return true;
			}
		}
	}
	return false;
}


/**
 * Ein Fahrzeug hat ein Problem erkannt und erzwingt die
 * Berechnung einer neuen Route
 * @author Hanjsrg Malthaner
 */
void convoi_t::suche_neue_route()
{
	state = ROUTING_1;
	wait_lock = 0;
}


/**
 * Asynchrne step methode des Convois
 * @author Hj. Malthaner
 */
void convoi_t::step()
{
	if(  wait_lock > 0  ) {
		return;
	}

	// moved check to here, as this will apply the same update
	// logic/constraints convois have for manual schedule manipulation
	if (line_update_pending.is_bound()) {
		check_pending_updates();
	}

	switch(state) {

		case LOADING:
			laden();
			break;

		case DUMMY4:
		case DUMMY5:
			break;

1194
		case EDIT_SCHEDULE:
1195
			// schedule window closed?
1196
			if(schedule!=NULL  &&  schedule->is_editing_finished()) {
1197

1198 1199
				set_schedule(schedule);
				schedule_target = koord3d::invalid;
1200

1201
				if(  schedule->empty()  ) {
1202 1203 1204 1205 1206 1207 1208 1209
					// no entry => no route ...
					state = NO_ROUTE;
					owner_p->report_vehicle_problem( self, koord3d::invalid );
				}
				else {
					// Schedule changed at station
					// this station? then complete loading task else drive on
					halthandle_t h = haltestelle_t::get_halt( get_pos(), get_owner() );
1210
					if(  h.is_bound()  &&  h==haltestelle_t::get_halt( schedule->get_current_entry().pos, get_owner() )  ) {
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
						if (route.get_count() > 0) {
							koord3d const& pos = route.back();
							if (h == haltestelle_t::get_halt(pos, get_owner())) {
								state = get_pos() == pos ? LOADING : DRIVING;
								break;
							}
						}
						else {
							if(  drive_to()  ) {
								state = DRIVING;
								break;
							}
						}
					}

1226
					if(  schedule->get_current_entry().pos==get_pos()  ) {
1227
						// position in depot: waiting
1228
						grund_t *gr = welt->lookup(schedule->get_current_entry().pos);
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
						if(  gr  &&  gr->get_depot()  ) {
							betrete_depot( gr->get_depot() );
						}
						else {
							state = ROUTING_1;
						}
					}
					else {
						// go to next
						state = ROUTING_1;
					}
				}
			}
			break;

		case ROUTING_1:
			{
				vehicle_t* v = fahr[0];

1248
				if(  schedule->empty()  ) {
1249 1250 1251 1252 1253
					state = NO_ROUTE;
					owner_p->report_vehicle_problem( self, koord3d::invalid );
				}
				else {
					// check first, if we are already there:
1254 1255 1256
					assert( schedule->get_current_stop()<schedule->get_count()  );
					if(  v->get_pos()==schedule->get_current_entry().pos  ) {
						schedule->advance();
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
					}
					// Hajo: now calculate a new route
					drive_to();
					// finally, was there a record last time?
					if(max_record_speed>welt->get_record_speed(fahr[0]->get_waytype())) {
						welt->notify_record(self, max_record_speed, record_pos);
					}
				}
			}
			break;

		case NO_ROUTE:
			// stuck vehicles
1270
			if (schedule->empty()) {
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
				// no entries => no route ...
			}
			else {
				// Hajo: now calculate a new route
				drive_to();
			}
			break;

		case CAN_START:
		case CAN_START_ONE_MONTH:
		case CAN_START_TWO_MONTHS:
			{
				vehicle_t* v = fahr[0];

				sint32 restart_speed = -1;
				if(  v->can_enter_tile( restart_speed, 0 )  ) {
					// can reserve new block => drive on
					state = (steps_driven>=0) ? LEAVING_DEPOT : DRIVING;
					if(haltestelle_t::get_halt(v->get_pos(),owner_p).is_bound()) {
						v->play_sound();
					}
				}
				else if(  steps_driven==0  ) {
					// on rail depot tile, do not reserve this
					if(  grund_t *gr = welt->lookup(fahr[0]->get_pos())  ) {
						if (schiene_t* const sch0 = obj_cast<schiene_t>(gr->get_weg(fahr[0]->get_waytype()))) {
							sch0->unreserve(fahr[0]);
						}
					}
				}
				if(restart_speed>=0) {
					akt_speed = restart_speed;
				}
				if(state==CAN_START  ||  state==CAN_START_ONE_MONTH) {
					set_tiles_overtaking( 0 );
				}
			}
			break;

		case WAITING_FOR_CLEARANCE_ONE_MONTH:
		case WAITING_FOR_CLEARANCE_TWO_MONTHS:
		case WAITING_FOR_CLEARANCE:
			{
				sint32 restart_speed = -1;
				if(  fahr[0]->can_enter_tile( restart_speed, 0 )  ) {
					state = (steps_driven>=0) ? LEAVING_DEPOT : DRIVING;
				}
				if(restart_speed>=0) {
					akt_speed = restart_speed;
				}
				if(state!=DRIVING) {
					set_tiles_overtaking( 0 );
				}
			}
			break;

		// must be here; may otherwise confuse window management
		case SELF_DESTRUCT:
			welt->set_dirty();
			destroy();
			return; // must not continue method after deleting this object

		default:	/* keeps compiler silent*/
			break;
	}

	// calculate new waiting time
	switch( state ) {
		// handled by routine
		case LOADING:
			break;

		// immediate action needed
		case SELF_DESTRUCT:
		case LEAVING_DEPOT:
		case ENTERING_DEPOT:
		case DRIVING:
		case DUMMY4:
		case DUMMY5:
			wait_lock = 0;
			break;

		// just waiting for action here
		case INITIAL:
1355
			welt->sync.remove(this);
1356
			/* FALLTHROUGH */
1357
		case EDIT_SCHEDULE:
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
		case NO_ROUTE:
			wait_lock = max( wait_lock, 25000 );
			break;

		// action soon needed
		case ROUTING_1:
		case CAN_START:
		case WAITING_FOR_CLEARANCE:
			wait_lock = max( wait_lock, 500 );
			break;

		// waiting for free way, not too heavy, not to slow
		case CAN_START_ONE_MONTH:
		case WAITING_FOR_CLEARANCE_ONE_MONTH:
		case CAN_START_TWO_MONTHS:
		case WAITING_FOR_CLEARANCE_TWO_MONTHS:
			wait_lock = 2500;
			break;
		default: ;
	}
}


1381
void convoi_t::new_year()
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
{
    jahresgewinn = 0;
}


void convoi_t::new_month()
{
	// should not happen: leftover convoi without vehicles ...
	if(anz_vehikel==0) {
		DBG_DEBUG("convoi_t::new_month()","no vehicles => self destruct!");
		self_destruct();
		return;
	}
	// update statistics of average speed
	if(  maxspeed_average_count==0  ) {
		financial_history[0][CONVOI_MAXSPEED] = distance_since_last_stop>0 ? get_speedbonus_kmh() : 0;
	}
	maxspeed_average_count = 0;
	// everything normal: update histroy
	for (int j = 0; j<MAX_CONVOI_COST; j++) {
		for (int k = MAX_MONTHS-1; k>0; k--) {
			financial_history[k][j] = financial_history[k-1][j];
		}
		financial_history[0][j] = 0;
	}
	// remind every new month again
	if(  state==NO_ROUTE  ) {
		get_owner()->report_vehicle_problem( self, get_pos() );
	}
	// check for traffic jam
	if(state==WAITING_FOR_CLEARANCE) {
		state = WAITING_FOR_CLEARANCE_ONE_MONTH;
		// check, if now free ...
		// might also reset the state!
		sint32 restart_speed = -1;
		if(  fahr[0]->can_enter_tile( restart_speed, 0 )  ) {
			state = DRIVING;
		}
		if(restart_speed>=0) {
			akt_speed = restart_speed;
		}
	}
	else if(state==WAITING_FOR_CLEARANCE_ONE_MONTH) {
		// make sure, not another vehicle with same line is loading in front
		bool notify = true;
		// check, if we are not waiting for load
		if(  line.is_bound()  &&  loading_level==0  ) {
			for(  uint i=0;  i < line->count_convoys();  i++  ) {
				convoihandle_t cnv = line->get_convoy(i);
				if(  cnv.is_bound()  &&  cnv->get_state()==LOADING  &&  cnv->get_loading_level() < cnv->get_loading_limit()  ) {
					// convoi on this line is waiting for load => assume we are waiting behind
					notify = false;
					break;
				}
			}
		}
		if(  notify  ) {
			get_owner()->report_vehicle_problem( self, koord3d::invalid );
		}
		state = WAITING_FOR_CLEARANCE_TWO_MONTHS;
	}
	// check for traffic jam
	if(state==CAN_START) {
		state = CAN_START_ONE_MONTH;
	}
	else if(state==CAN_START_ONE_MONTH  ||  state==CAN_START_TWO_MONTHS  ) {
		get_owner()->report_vehicle_problem( self, koord3d::invalid );
		state = CAN_START_TWO_MONTHS;
	}
	// check for obsolete vehicles in the convoi
	if(!has_obsolete  &&  welt->use_timeline()) {
		// convoi has obsolete vehicles?
		const int month_now = welt->get_timeline_year_month();
		has_obsolete = false;
1456 1457
		for(unsigned j=0;  j<get_vehicle_count();  j++ ) {
			if (fahr[j]->get_desc()->is_retired(month_now)) {
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
				has_obsolete = true;
				break;
			}
		}
	}
}


void convoi_t::betrete_depot(depot_t *dep)
{
	// first remove reservation, if train is still on track
	unreserve_route();

	// Hajo: remove vehicles from world data structure
	for(unsigned i=0; i<anz_vehikel; i++) {
		vehicle_t* v = fahr[i];

		grund_t* gr = welt->lookup(v->get_pos());
		if(gr) {
			// remove from blockstrecke
			v->set_last(true);
			v->leave_tile();
			v->set_flag( obj_t::not_on_map );
		}
	}

	dep->convoi_arrived(self, get_schedule());

	destroy_win( magic_convoi_info+self.get_id() );
	destroy_win( magic_convoi_detail+self.get_id() );

	maxspeed_average_count = 0;
	state = INITIAL;
}


void convoi_t::start()
{
	if(state == INITIAL || state == ROUTING_1) {

		// set home depot to location of depot convoi is leaving
		if(route.empty()) {
			home_depot = fahr[0]->get_pos();
		}
		else {
			home_depot = route.front();
			fahr[0]->set_pos( home_depot );
		}
		// put the convoi on the depot ground, to get automatic rotation
		// (vorfahren() will remove it anyway again.)
		grund_t *gr = welt->lookup( home_depot );
		assert(gr);
		gr->obj_add( fahr[0] );

		// put into sync list
1513
		welt->sync.add(this);
1514

1515
		alte_richtung = ribi_t::none;
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
		no_load = false;

		state = ROUTING_1;

		// recalc weight and image
		// also for any vehicle entered a depot, set_letztes is true! => reset it correctly
		sint64 restwert_delta = 0;
		for(unsigned i=0; i<anz_vehikel; i++) {
			fahr[i]->set_leading( false );
			fahr[i]->set_last( false );
			restwert_delta -= fahr[i]->calc_sale_value();
			fahr[i]->set_driven();
			restwert_delta += fahr[i]->calc_sale_value();
			fahr[i]->clear_flag( obj_t::not_on_map );
		}
		fahr[0]->set_leading( true );
		fahr[anz_vehikel-1]->set_last( true );
		// do not show the vehicle - it will be wrong positioned -vorfahren() will correct this
1534
		fahr[0]->set_image(IMG_EMPTY);
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581

		// update finances for used vehicle reduction when first driven
		owner_p->update_assets( restwert_delta, get_schedule()->get_waytype());

		// calc state for convoi
		calc_loading();
		calc_speedbonus_kmh();
		maxspeed_average_count = 0;

		if(line.is_bound()) {
			// might have changed the vehicles in this car ...
			line->recalc_catg_index();
		}
		else {
			welt->set_schedule_counter();
		}
		wait_lock = 0;

		DBG_MESSAGE("convoi_t::start()","Convoi %s wechselt von INITIAL nach ROUTING_1", name_and_id);
	}
	else {
		dbg->warning("convoi_t::start()","called with state=%s\n",state_names[state]);
	}
}


/* called, when at a destination
 * can be waypoint, depot or a stop
 * called from the first vehicle_t of a convoi */
void convoi_t::ziel_erreicht()
{
	const vehicle_t* v = fahr[0];
	alte_richtung = v->get_direction();

	// check, what is at destination!
	const grund_t *gr = welt->lookup(v->get_pos());
	depot_t *dp = gr->get_depot();

	if(dp) {
		// ok, we are entering a depot
		cbuffer_t buf;

		// we still book the money for the trip; however, the freight will be deleted (by the vehicle in the depot itself)
		calc_gewinn();

		akt_speed = 0;
		buf.printf( translator::translate("%s has entered a depot."), get_name() );
1582
		welt->get_message()->add_message(buf, v->get_pos().get_2d(),message_t::warnings, PLAYER_FLAG|get_owner()->get_player_nr(), IMG_EMPTY);
1583 1584 1585 1586 1587

		betrete_depot(dp);
	}
	else {
		// no depot reached, check for stop!
1588
		halthandle_t halt = haltestelle_t::get_halt(schedule->get_current_entry().pos,owner_p);
1589 1590 1591 1592 1593
		if(  halt.is_bound() &&  gr->get_weg_ribi(v->get_waytype())!=0  ) {
			// seems to be a stop, so book the money for the trip
			akt_speed = 0;
			halt->book(1, HALT_CONVOIS_ARRIVED);
			state = LOADING;
1594
			arrived_time = welt->get_ticks();
1595 1596 1597
		}
		else {
			// Neither depot nor station: waypoint
1598
			schedule->advance();
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
			state = ROUTING_1;
		}
	}
	wait_lock = 0;
}


/**
 * Wartet bis Fahrzeug 0 freie Fahrt meldet
 * @author Hj. Malthaner
 */
void convoi_t::warten_bis_weg_frei(sint32 restart_speed)
{
	if(!is_waiting()) {
		state = WAITING_FOR_CLEARANCE;
		wait_lock = 0;
	}
	if(restart_speed>=0) {
		// langsam anfahren
		akt_speed = restart_speed;
	}
}


bool convoi_t::add_vehikel(vehicle_t *v, bool infront)
{
1625 1626 1627 1628 1629
DBG_MESSAGE("convoi_t::add_vehikel()","at pos %i of %i total vehikels.",anz_vehikel,fahr.get_count());
	// extend array if requested
	if(anz_vehikel == fahr.get_count()) {
		fahr.resize(anz_vehikel+1,NULL);
DBG_MESSAGE("convoi_t::add_vehikel()","extend array_tpl to %i totals.",fahr.get_count());
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
	}
	// now append
	if (anz_vehikel < fahr.get_count()) {
		v->set_convoi(this);

		if(infront) {
			for(unsigned i = anz_vehikel; i > 0; i--) {
				fahr[i] = fahr[i - 1];
			}
			fahr[0] = v;
		} else {
			fahr[anz_vehikel] = v;
		}
		anz_vehikel ++;

1645 1646 1647
		const vehicle_desc_t *info = v->get_desc();
		if(info->get_power()) {
			is_electric |= info->get_engine_type()==vehicle_desc_t::electric;
1648
		}
1649 1650 1651 1652 1653 1654
		sum_power += info->get_power();
		sum_gear_and_power += info->get_power()*info->get_gear();
		sum_weight += info->get_weight();
		sum_running_costs -= info->get_running_cost();
		min_top_speed = min( min_top_speed, kmh_to_speed( v->get_desc()->get_topspeed() ) );
		sum_gesamtweight = sum_weight;
1655 1656 1657 1658
		calc_loading();
		freight_info_resort = true;
		// Add good_catg_index:
		if(v->get_cargo_max() != 0) {
1659 1660
			const goods_desc_t *ware=v->get_cargo_type();
			if(ware!=goods_manager_t::none  ) {
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
				goods_catg_index.append_unique( ware->get_catg_index() );
			}
		}
		// check for obsolete
		if(!has_obsolete  &&  welt->use_timeline()) {
			has_obsolete = info->is_retired( welt->get_timeline_year_month() );
		}
		player_t::add_maintenance( get_owner(), info->get_maintenance(), info->get_waytype() );
	}
	else {
		return false;
	}

	// der convoi hat jetzt ein neues ende
	set_erstes_letztes();

1677
DBG_MESSAGE("convoi_t::add_vehikel()","now %i of %i total vehikels.",anz_vehikel,fahr.get_count());
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
	return true;
}


vehicle_t *convoi_t::remove_vehikel_bei(uint16 i)
{
	vehicle_t *v = NULL;
	if(i<anz_vehikel) {
		v = fahr[i];
		if(v != NULL) {
			for(unsigned j=i; j<anz_vehikel-1u; j++) {
				fahr[j] = fahr[j + 1];
			}

			v->set_convoi(NULL);

			--anz_vehikel;
			fahr[anz_vehikel] = NULL;

1697 1698 1699 1700 1701
			const vehicle_desc_t *info = v->get_desc();
			sum_power -= info->get_power();
			sum_gear_and_power -= info->get_power()*info->get_gear();
			sum_weight -= info->get_weight();
			sum_running_costs += info->get_running_cost();
1702 1703
			player_t::add_maintenance( get_owner(), -info->get_maintenance(), info->get_waytype() );
		}
1704
		sum_gesamtweight = sum_weight;
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
		calc_loading();
		freight_info_resort = true;

		// der convoi hat jetzt ein neues ende
		if(anz_vehikel > 0) {
			set_erstes_letztes();
		}

		// Hajo: calculate new minimum top speed
		min_top_speed = calc_min_top_speed(fahr, anz_vehikel);

		// check for obsolete
		if(has_obsolete) {
			has_obsolete = false;
			const int month_now = welt->get_timeline_year_month();
			for(unsigned i=0; i<anz_vehikel; i++) {
1721
				has_obsolete |= fahr[i]->get_desc()->is_retired(month_now);
1722 1723 1724 1725 1726 1727 1728 1729 1730
			}
		}

		recalc_catg_index();

		// still requires electrifications?
		if(is_electric) {
			is_electric = false;
			for(unsigned i=0; i<anz_vehikel; i++) {
1731 1732
				if(fahr[i]->get_desc()->get_power()) {
					is_electric |= fahr[i]->get_desc()->get_engine_type()==vehicle_desc_t::electric;
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
				}
			}
		}
	}
	return v;
}


// recalc what good this convoy is moving
void convoi_t::recalc_catg_index()
{
	goods_catg_index.clear();

1746
	for(  uint8 i = 0;  i < get_vehicle_count();  i++  ) {
1747 1748 1749 1750 1751 1752
		// Only consider vehicles that really transport something
		// this helps against routing errors through passenger
		// trains pulling only freight wagons
		if(get_vehikel(i)->get_cargo_max() == 0) {
			continue;
		}
1753 1754
		const goods_desc_t *ware=get_vehikel(i)->get_cargo_type();
		if(ware!=goods_manager_t::none  ) {
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
			goods_catg_index.append_unique( ware->get_catg_index() );
		}
	}
	/* since during composition of convois all kinds of composition could happen,
	 * we do not enforce schedule recalculation here; it will be done anyway all times when leaving the INTI state ...
	 */
}


void convoi_t::set_erstes_letztes()
{
	// anz_vehikel muss korrekt init sein
	if(anz_vehikel>0) {
		fahr[0]->set_leading(true);
		for(unsigned i=1; i<anz_vehikel; i++) {
			fahr[i]->set_leading(false);
			fahr[i - 1]->set_last(false);
		}
		fahr[anz_vehikel - 1]->set_last(true);
	}
	else {
		dbg->warning("convoi_t::set_erstes_letzes()", "called with anz_vehikel==0!");
	}
}


// remove wrong freight when schedule changes etc.
void convoi_t::check_freight()
{
	for(unsigned i=0; i<anz_vehikel; i++) {
		fahr[i]->remove_stale_cargo();
	}
	calc_loading();
	freight_info_resort = true;
}


bool convoi_t::set_schedule(schedule_t * f)
{
	if(  state==SELF_DESTRUCT  ) {
		return false;
	}

1798
	DBG_DEBUG("convoi_t::set_schedule()", "new=%p, old=%p", f, schedule);
1799 1800 1801
	assert(f != NULL);

	// happens to be identical?
1802
	if(schedule!=f) {
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
		// now check, we we have been bond to a line we are about to lose:
		bool changed = false;
		if(  line.is_bound()  ) {
			if(  !f->matches( welt, line->get_schedule() )  ) {
				// change from line to individual schedule
				//		-> unset line now and register stops from new schedule later
				changed = true;
				unset_line();
			}
		}
		else {
1814
			if(  !f->matches( welt, schedule )  ) {
1815 1816 1817 1818 1819 1820 1821
				// Knightly : merely change schedule and do not involve line
				//				-> unregister stops from old schedule now and register stops from new schedule later
				changed = true;
				unregister_stops();
			}
		}
		// destroy a possibly open schedule window
1822 1823 1824
		if(  schedule  &&  !schedule->is_editing_finished()  ) {
			destroy_win((ptrdiff_t)schedule);
			delete schedule;
1825
		}
1826
		schedule = f;
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
		if(  changed  ) {
			// Knightly : if line is unset or schedule is changed
			//				-> register stops from new schedule
			register_stops();
			welt->set_schedule_counter();	// must trigger refresh
		}
	}

	// remove wrong freight
	check_freight();

	// ok, now we have a schedule
1839 1840
	if(state != INITIAL) {
		state = EDIT_SCHEDULE;
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
	}
	// to avoid jumping trains
	alte_richtung = fahr[0]->get_direction();
	wait_lock = 0;
	return true;
}


schedule_t *convoi_t::create_schedule()
{
1851
	if(schedule == NULL) {
1852 1853 1854
		const vehicle_t* v = fahr[0];

		if (v != NULL) {
1855 1856
			schedule = v->generate_new_schedule();
			schedule->finish_editing();
1857 1858 1859
		}
	}

1860
	return schedule;
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
}


/* checks, if we go in the same direction;
 * true: convoy prepared
 * false: must recalculate position
 * on all error we better use the normal starting procedure ...
 */
bool convoi_t::can_go_alte_richtung()
{
	// invalid route? nothing to test, must start new
	if(route.empty()) {
		return false;
	}

	// going backwards? then recalculate all
1877 1878
	ribi_t::ribi neue_richtung_rwr = ribi_t::backward(fahr[0]->calc_direction(route.front(), route.at(min(2, route.get_count() - 1))));
//	DBG_MESSAGE("convoi_t::go_alte_richtung()","neu=%i,rwr_neu=%i,alt=%i",neue_richtung_rwr,ribi_t::backward(neue_richtung_rwr),alte_richtung);
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
	if(neue_richtung_rwr&alte_richtung) {
		akt_speed = 8;
		return false;
	}

	// now get the actual length and the tile length
	uint16 convoi_length = 15;
	uint16 tile_length = 24;
	unsigned i;	// for visual C++
	const vehicle_t* pred = NULL;
	for(i=0; i<anz_vehikel; i++) {
		const vehicle_t* v = fahr[i];
		grund_t *gr = welt->lookup(v->get_pos());

		// not last vehicle?
		// the length of last vehicle does not matter when it comes to positioning of vehicles
		if ( i+1 < anz_vehikel) {
1896
			convoi_length += v->get_desc()->get_length();
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
		}

		if(gr==NULL  ||  (pred!=NULL  &&  (abs(v->get_pos().x-pred->get_pos().x)>=2  ||  abs(v->get_pos().y-pred->get_pos().y)>=2))  ) {
			// ending here is an error!
			// this is an already broken train => restart
			dbg->warning("convoi_t::go_alte_richtung()","broken convoy (id %i) found => fixing!",self.get_id());
			akt_speed = 8;
			return false;
		}

		// now check, if ribi is straight and train is not
		ribi_t::ribi weg_ribi = gr->get_weg_ribi_unmasked(v->get_waytype());
1909
		if(ribi_t::is_straight(weg_ribi)  &&  (weg_ribi|v->get_direction())!=weg_ribi) {
1910 1911 1912 1913 1914 1915
			dbg->warning("convoi_t::go_alte_richtung()","convoy with wrong vehicle directions (id %i) found => fixing!",self.get_id());
			akt_speed = 8;
			return false;
		}

		if(  pred  &&  pred->get_pos()!=v->get_pos()  ) {
1916
			tile_length += (ribi_t::is_straight(welt->lookup(pred->get_pos())->get_weg_ribi_unmasked(pred->get_waytype())) ? 16 : 8192/vehicle_t::get_diagonal_multiplier())*koord_distance(pred->get_pos(),v->get_pos());
1917 1918 1919 1920 1921
		}

		pred = v;
	}
	// check if convoi is way too short (even for diagonal tracks)
1922
	tile_length += (ribi_t::is_straight(welt->lookup(fahr[anz_vehikel-1]->get_pos())->get_weg_ribi_unmasked(fahr[anz_vehikel-1]->get_waytype())) ? 16 : 8192/vehicle_t::get_diagonal_multiplier());
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
	if(  convoi_length>tile_length  ) {
		dbg->warning("convoi_t::go_alte_richtung()","convoy too short (id %i) => fixing!",self.get_id());
		akt_speed = 8;
		return false;
	}

	uint16 length = min((convoi_length/16u)+4u,route.get_count());	// maximum length in tiles to check

	// we just check, whether we go back (i.e. route tiles other than zero have convoi vehicles on them)
	for( int index=1;  index<length;  index++ ) {
1933
		grund_t *gr=welt->lookup(route.at(index));
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
		// now check, if we are already here ...
		for(unsigned i=0; i<anz_vehikel; i++) {
			if (gr->obj_ist_da(fahr[i])) {
				// we are turning around => start slowly and rebuilt train
				akt_speed = 8;
				return false;
			}
		}
	}

//DBG_MESSAGE("convoi_t::go_alte_richtung()","alte=%d, neu_rwr=%d",alte_richtung,neue_richtung_rwr);

	// we continue our journey; however later cars need also a correct route entry
	// eventually we need to add their positions to the convois route
	koord3d pos = fahr[0]->get_pos();
	assert(pos == route.front());
	if(welt->lookup(pos)->get_depot()) {
		return false;
	}
	else {
		for(i=0; i<anz_vehikel; i++) {
			vehicle_t* v = fahr[i];
			// eventually add current position to the route
1957
			if (route.front() != v->get_pos() && route.at(1) != v->get_pos()) {
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
				route.insert(v->get_pos());
			}
		}
	}

	// since we need the route for every vehicle of this convoi,
	// we must set the current route index (instead assuming 1)
	length = min((convoi_length/8u),route.get_count()-1);	// maximum length in tiles to check
	bool ok=false;
	for(i=0; i<anz_vehikel; i++) {
		vehicle_t* v = fahr[i];

		// this is such awkward, since it takes into account different vehicle length
		const koord3d vehicle_start_pos = v->get_pos();
		for( int idx=0;  idx<=length;  idx++  ) {
1973
			if(route.at(idx)==vehicle_start_pos) {
1974 1975 1976 1977 1978 1979
				// set route index, no recalculations necessary
				v->initialise_journey(idx, false );
				ok = true;

				// check direction
				uint8 richtung = v->get_direction();
1980
				uint8 neu_richtung = v->calc_direction( route.at(max(idx-1,0)), v->get_pos_next());
1981
				// we need to move to this place ...
1982
				if(neu_richtung!=richtung  &&  (i!=0  ||  anz_vehikel==1  ||  ribi_t::is_bend(neu_richtung)) ) {
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
					// 90 deg bend!
					return false;
				}

				break;
			}
		}
		// too short?!? (rather broken then!)
		if(!ok) {
			return false;
		}
	}

	return true;
}


// put the convoi on its way
void convoi_t::vorfahren()
{
	// Hajo: init speed settings
	sp_soll = 0;
	set_tiles_overtaking( 0 );
	recalc_data_front = true;
	recalc_data = true;

	koord3d k0 = route.front();
	grund_t *gr = welt->lookup(k0);
	bool at_dest = false;
	if(gr  &&  gr->get_depot()) {
		// start in depot
		for(unsigned i=0; i<anz_vehikel; i++) {
			vehicle_t* v = fahr[i];

			// remove from old position
			grund_t* gr = welt->lookup(v->get_pos());
			if(gr) {
				gr->obj_remove(v);
				if(gr->ist_uebergang()) {
					crossing_t *cr = gr->find<crossing_t>(2);
					cr->release_crossing(v);
				}
				// eventually unreserve this
				if(  schiene_t* const sch0 = obj_cast<schiene_t>(gr->get_weg(fahr[i]->get_waytype()))  ) {
					sch0->unreserve(v);
				}
			}
			v->initialise_journey(0, true);
			// set at new position
			gr = welt->lookup(v->get_pos());
			assert(gr);
			v->enter_tile(gr);
		}

		// just advances the first vehicle
		vehicle_t* v0 = fahr[0];
		v0->set_leading(false); // switches off signal checks ...
		v0->get_smoke(false);
		steps_driven = 0;
		// drive half a tile:
		for(int i=0; i<anz_vehikel; i++) {
			fahr[i]->do_drive( (VEHICLE_STEPS_PER_TILE/2)<<YARDS_PER_VEHICLE_STEP_SHIFT );
		}
		v0->get_smoke(true);
		v0->set_leading(true); // switches on signal checks to reserve the next route

		// until all other are on the track
		state = CAN_START;
	}
	else {
		// still leaving depot (steps_driven!=0) or going in other direction or misalignment?
		if(  steps_driven>0  ||  !can_go_alte_richtung()  ) {

			// start route from the beginning at index 0, place everything on start
			uint32 train_length = move_to(0);

			// move one train length to the start position ...
			// in north/west direction, we leave the vehicle away to start as much back as possible
			ribi_t::ribi neue_richtung = fahr[0]->get_direction();
2062
			if(neue_richtung==ribi_t::south  ||  neue_richtung==ribi_t::east) {
2063 2064 2065
				// drive the convoi to the same position, but do not hop into next tile!
				if(  train_length%16==0  ) {
					// any space we need => just add
2066
					train_length += fahr[anz_vehikel-1]->get_desc()->get_length();
2067 2068 2069
				}
				else {
					// limit train to front of tile
2070
					train_length += min( (train_length%CARUNITS_PER_TILE)-1, fahr[anz_vehikel-1]->get_desc()->get_length() );
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
				}
			}
			else {
				train_length += 1;
			}
			train_length = max(1,train_length);

			// now advance all convoi until it is completely on the track
			fahr[0]->set_leading(false); // switches off signal checks ...
			uint32 dist = VEHICLE_STEPS_PER_CARUNIT*train_length<<YARDS_PER_VEHICLE_STEP_SHIFT;
			for(unsigned i=0; i<anz_vehikel; i++) {
				vehicle_t* v = fahr[i];

				v->get_smoke(false);
				uint32 const driven = fahr[i]->do_drive( dist );
				if (i==0  &&  driven < dist) {
					// we are already at our destination
					at_dest = true;
				}
				// this gives the length in carunits, 1/CARUNITS_PER_TILE of a full tile => all cars closely coupled!
				v->get_smoke(true);

2093
				uint32 const vlen = ((VEHICLE_STEPS_PER_CARUNIT*v->get_desc()->get_length())<<YARDS_PER_VEHICLE_STEP_SHIFT);
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
				if (vlen > dist) {
					break;
				}
				dist = driven - vlen;
			}
			fahr[0]->set_leading(true);
		}
		if (!at_dest) {
			state = CAN_START;

			// to advance more smoothly
			sint32 restart_speed = -1;
			if(  fahr[0]->can_enter_tile( restart_speed, 0 )  ) {
				// can reserve new block => drive on
				if(haltestelle_t::get_halt(k0,owner_p).is_bound()) {
					fahr[0]->play_sound();
				}
				state = DRIVING;
			}
		}
		else {
			ziel_erreicht();
		}
	}

	// finally reserve route (if needed)
	if(  fahr[0]->get_waytype()!=air_wt  &&  !at_dest  ) {
		// do not pre-reserve for airplanes
		for(unsigned i=0; i<anz_vehikel; i++) {
			// eventually reserve this
			vehicle_t const& v = *fahr[i];
			if (schiene_t* const sch0 = obj_cast<schiene_t>(welt->lookup(v.get_pos())->get_weg(v.get_waytype()))) {
2126
				sch0->reserve(self,ribi_t::none);
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
			}
			else {
				break;
			}
		}
	}

	wait_lock = 0;
	INT_CHECK("simconvoi 711");
}


void convoi_t::rdwr_convoihandle_t(loadsave_t *file, convoihandle_t &cnv)
{
	if(  file->get_version()>112002  ) {
		uint16 id = (file->is_saving()  &&  cnv.is_bound()) ? cnv.get_id() : 0;
		file->rdwr_short( id );
		if (file->is_loading()) {
			cnv.set_id( id );
		}
	}
}


void convoi_t::rdwr(loadsave_t *file)
{
	xml_tag_t t( file, "convoi_t" );

	sint32 dummy;
	sint32 owner_n = welt->sp2num(owner_p);

	if(file->is_saving()) {
		if(  file->get_version()<101000  ) {
			file->wr_obj_id("Convoi");
			// the matching read is in karte_t::laden(loadsave*)...
		}
	}

	// do the update, otherwise we might lose the line after save & reload
	if(file->is_saving()  &&  line_update_pending.is_bound()) {
		check_pending_updates();
	}

	simline_t::rdwr_linehandle_t(file, line);

	// we want persistent convoihandles so we can keep dialogues open in network games
	if(  file->is_loading()  ) {
		if(  file->get_version()<=112002  ) {
			self = convoihandle_t( this );
		}
		else {
			uint16 id;
			file->rdwr_short( id );
			self = convoihandle_t( this, id );
		}
	}
	else if(  file->get_version()>112002  ) {
		uint16 id = self.get_id();
		file->rdwr_short( id );
	}

	dummy = anz_vehikel;
	file->rdwr_long(dummy);
	anz_vehikel = (uint8)dummy;

	if(file->get_version()<99014) {
		// was anz_ready
		file->rdwr_long(dummy);
	}

	file->rdwr_long(wait_lock);
	// some versions may produce broken safegames apparently
	if(wait_lock > 60000) {
		dbg->warning("convoi_t::sync_prepre()","Convoi %d: wait lock out of bounds: wait_lock = %d, setting to 60000",self.get_id(), wait_lock);
		wait_lock = 60000;
	}

	bool dummy_bool=false;
	file->rdwr_bool(dummy_bool);
	file->rdwr_long(owner_n);
	file->rdwr_long(akt_speed);
	file->rdwr_long(akt_speed_soll);
	file->rdwr_long(sp_soll);
	file->rdwr_enum(state);
	file->rdwr_enum(alte_richtung);

	// read the yearly income (which has since then become a 64 bit value)
	// will be recalculated later directly from the history
	if(file->get_version()<=89003) {
		file->rdwr_long(dummy);
	}

	route.rdwr(file);

	if(file->is_loading()) {
		// extend array if requested (only needed for trains)
Jörg Frings-Fürst's avatar