forked from aburch/simutrans
-
Notifications
You must be signed in to change notification settings - Fork 1
/
simconvoi.cc
3669 lines (3218 loc) · 102 KB
/
simconvoi.cc
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
28
29
30
31
32
33
34
35
36
37
38
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
74
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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
169
170
171
172
173
174
175
176
177
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
358
359
360
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
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
553
554
555
556
557
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
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
918
919
920
921
922
923
924
925
926
927
928
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
956
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
995
996
997
998
999
1000
/**
* convoi_t Klasse für Fahrzeugverbände
* von Hansjörg 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 "simtools.h"
#include "freight_list_sorter.h"
#include "gui/karte.h"
#include "gui/convoi_info_t.h"
#include "gui/fahrplan_gui.h"
#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
#include "besch/vehikel_besch.h"
#include "besch/roadsign_besch.h"
#include "dataobj/fahrplan.h"
#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/simvehikel.h"
#include "vehicle/overtaker.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",
"FAHRPLANEINGABE",
"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<vehikel_t*>& fahr, uint8 anz_vehikel)
{
int min_top_speed = SPEED_UNLIMITED;
for(uint8 i=0; i<anz_vehikel; i++) {
min_top_speed = min(min_top_speed, kmh_to_speed( fahr[i]->get_besch()->get_geschw() ) );
}
return min_top_speed;
}
void convoi_t::init(spieler_t *sp)
{
besitzer_p = sp;
is_electric = false;
sum_running_costs = sum_gesamtgewicht = sum_gewicht = sum_gear_und_leistung = sum_leistung = 0;
previous_delta_v = 0;
min_top_speed = SPEED_UNLIMITED;
speedbonus_kmh = SPEED_UNLIMITED; // speed_to_kmh() not needed
fpl = NULL;
fpl_target = koord3d::invalid;
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;
alte_richtung = ribi_t::keine;
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;
max_record_speed = 0;
brake_speed_soll = SPEED_UNLIMITED;
akt_speed_soll = 0; // Sollgeschwindigkeit
akt_speed = 0; // momentane Geschwindigkeit
sp_soll = 0;
next_stop_index = 65535;
line_update_pending = linehandle_t();
home_depot = koord3d::invalid;
// last_stop_pos = koord3d::invalid;
recalc_data_front = true;
recalc_data = true;
}
convoi_t::convoi_t(loadsave_t* file) : fahr(max_vehicle, NULL)
{
self = convoihandle_t();
init(0);
rdwr(file);
}
convoi_t::convoi_t(spieler_t* sp) : fahr(max_vehicle, NULL)
{
self = convoihandle_t(this);
sp->book_convoi_number(1);
init(sp);
set_name( "Unnamed" );
welt->add_convoi( self );
init_financial_history();
}
convoi_t::~convoi_t()
{
besitzer_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() );
}
welt->sync_remove( this );
welt->rem_convoi( self );
// Knightly : if lineless convoy -> unregister from stops
if( !line.is_bound() ) {
unregister_stops();
}
// force asynchronous recalculation
if(fpl) {
if(!fpl->ist_abgeschlossen()) {
destroy_win((ptrdiff_t)fpl);
}
if (!fpl->empty() && !line.is_bound()) {
welt->set_schedule_counter();
}
delete fpl;
}
// @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) {
grund_t *gr = welt->lookup_kartenboden(ziel.get_2d());
if( gr == NULL || gr->get_weg(air_wt) == NULL ) {
return true;
}
}
return !haltestelle_t::get_halt(ziel,get_besitzer()).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 ) {
waggon_t* lok = dynamic_cast<waggon_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);
}
}
}
/**
* unreserves the whole remaining route
*/
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++ ) {
if( grund_t *gr = welt->lookup( route.position_bei(idx) ) ) {
if( schiene_t *sch = (schiene_t *)gr->get_weg( front()->get_waytype() ) ) {
sch->reserve( self, ribi_typ( route.position_bei(max(1u,idx)-1u), route.position_bei(min(route.get_count()-1u,idx+1u)) ) );
}
}
}
}
}
uint32 convoi_t::move_to(koord3d const& k, uint16 const start_index)
{
uint32 train_length = 0;
for (unsigned i = 0; i != anz_vehikel; ++i) {
vehikel_t& v = *fahr[i];
steps_driven = -1;
if( grund_t const* gr = welt->lookup(v.get_pos()) ) {
v.mark_image_dirty(v.get_bild(), 0);
v.verlasse_feld();
// maybe unreserve this
if( schiene_t* const rails = obj_cast<schiene_t>(gr->get_weg(v.get_waytype())) ) {
rails->unreserve(&v);
}
}
/* Set pos_prev to the starting point this way. Otherwise it may be
* elsewhere, especially on curves and with already broken convois. */
v.set_pos(k);
v.neue_fahrt(start_index, true);
if (welt->lookup(v.get_pos())) {
v.set_pos(k);
v.betrete_feld();
}
if (i != anz_vehikel - 1U) {
train_length += v.get_besch()->get_length();
}
}
return train_length;
}
void convoi_t::laden_abschliessen()
{
if(fpl==NULL) {
if( state!=INITIAL ) {
grund_t *gr = welt->lookup(home_depot);
if(gr && gr->get_depot()) {
dbg->warning( "convoi_t::laden_abschliessen()","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::laden_abschliessen()","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++ ) {
vehikel_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
const koord3d ziel = fpl->get_current_eintrag().pos;
if( anz_vehikel>0 && is_waypoint(ziel) ) {
fpl_target = ziel;
}
}
bool realing_position = false;
if( anz_vehikel>0 ) {
DBG_MESSAGE("convoi_t::laden_abschliessen()","state=%s, next_stop_index=%d", state_names[state] );
// only realign convois not leaving depot to avoid jumps through signals
if( steps_driven!=-1 ) {
for( uint8 i=0; i<anz_vehikel; i++ ) {
vehikel_t* v = fahr[i];
v->set_erstes( i==0 );
v->set_letztes( i+1==anz_vehikel );
// 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++ ) {
vehikel_t* v = fahr[i];
v->set_erstes( i==0 );
v->set_letztes( i+1==anz_vehikel );
// 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
realing_position |= ribi_t::ist_kurve(v->get_fahrtrichtung()) && (state==DRIVING || is_waiting());
}
// 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;
}
step_pos += ribi_t::ist_kurve(v->get_fahrtrichtung()) ? diagonal_vehicle_steps_per_tile : VEHICLE_STEPS_PER_TILE;
}
dbg->message("convoi_t::laden_abschliessen()", "v: pos(%s) steps(%d) len=%d ribi=%d prev (%s) step(%d)", v->get_pos().get_str(), v->get_steps(), v->get_besch()->get_length()*16, v->get_fahrtrichtung(), drive_pos.get_2d().get_str(), step_pos);
if( abs( v->get_steps() - step_pos )>15 ) {
// not where it should be => realing
realing_position = true;
dbg->warning( "convoi_t::laden_abschliessen()", "convoi (%s) is broken => realign", get_name() );
}
}
step_pos -= v->get_besch()->get_length_in_steps();
drive_pos = v->get_pos();
}
}
}
DBG_MESSAGE("convoi_t::laden_abschliessen()","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_besitzer()->simlinemgmt.get_line_with_id_zero();
}
if( new_line.is_bound() ) {
if ( !fpl->matches( welt, new_line->get_schedule() ) ) {
// 101 version produced broken line ids => we have to find our line the hard way ...
vector_tpl<linehandle_t> lines;
get_besitzer()->simlinemgmt.get_lines(fpl->get_type(), &lines);
new_line = linehandle_t();
FOR(vector_tpl<linehandle_t>, const l, lines) {
if( fpl->matches( welt, l->get_schedule() ) ) {
// 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::laden_abschliessen()","%s registers for %d", name_and_id, line.get_id());
}
else {
line = linehandle_t();
}
}
}
else {
// no vehicles in this convoi?!?
dbg->error( "convoi_t::laden_abschliessen()","No vehicles in Convoi %i: will be destroyed!", self.get_id() );
destroy();
return;
}
// put convoi agian right on track?
if(realing_position && anz_vehikel>1) {
// display just a warning
dbg->warning("convoi_t::laden_abschliessen()","cnv %i is currently too long.",self.get_id());
if (route.empty()) {
// realigning needs a route
state = NO_ROUTE;
besitzer_p->bescheid_vehikel_problem( self, koord3d::invalid );
dbg->error( "convoi_t::laden_abschliessen()", "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(2,fahr[anz_vehikel-1]->get_route_index())-2;
koord3d k0 = fahr[anz_vehikel-1]->get_pos();
uint32 train_length = move_to(k0, 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_erstes(false); // switches off signal checks ...
for(unsigned i=0; i<anz_vehikel; i++) {
vehikel_t* v = fahr[i];
v->darf_rauchen(false);
fahr[i]->fahre_basis( (VEHICLE_STEPS_PER_CARUNIT*train_length)<<YARDS_PER_VEHICLE_STEP_SHIFT );
train_length -= v->get_besch()->get_length();
v->darf_rauchen(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()))) {
sch0->reserve(self,ribi_t::keine);
}
}
fahr[0]->set_erstes(true);
if( state != INITIAL && state != FAHRPLANEINGABE && fahr[0]->get_pos() != last_start ) {
state = WAITING_FOR_CLEARANCE;
}
}
}
if( state==LOADING ) {
// the fully the shorter => reregister as older convoi
wait_lock = 2000-loading_level*20;
}
// when saving with open window, this can happen
if( state==FAHRPLANEINGABE ) {
if (env_t::networkmode) {
wait_lock = 30000; // 60s to drive on, if the client in question had left
}
fpl->eingabe_abschliessen();
}
// remove wrong freight
check_freight();
// some convois had wrong old direction in them
if( state<DRIVING || state==LOADING ) {
alte_richtung = fahr[0]->get_fahrtrichtung();
}
// Knightly : if lineless convoy -> register itself with stops
if( !line.is_bound() ) {
register_stops();
}
calc_speedbonus_kmh();
}
// since now convoi states go via werkzeug_t
void convoi_t::call_convoi_tool( const char function, const char *extra ) const
{
werkzeug_t *w = create_tool( WKZ_CONVOI_TOOL | SIMPLE_TOOL );
cbuffer_t param;
param.printf("%c,%u", function, self.get_id());
if( extra && *extra ) {
param.printf(",%s", extra);
}
w->set_default_param(param);
welt->set_werkzeug( w, get_besitzer() );
// since init always returns false, it is safe to delete immediately
delete w;
}
void convoi_t::rotate90( const sint16 y_size )
{
// last_stop_pos.rotate90( y_size );
record_pos.rotate90( y_size );
home_depot.rotate90( y_size );
route.rotate90( y_size );
if( fpl_target!=koord3d::invalid ) {
fpl_target.rotate90( y_size );
}
if(fpl) {
fpl->rotate90( y_size );
}
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();
}
/**
* Gibt die Position des Convois zurück.
* @return Position des Convois
* @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++ ) {
len += fahr[i]->get_besch()->get_length();
}
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_besitzer()!=get_besitzer() && weg->get_besitzer()!=NULL ) {
// running on non-public way costs toll (since running costas 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() ) {
toll += (wo->get_besch()->get_wartung()*welt->get_settings().get_way_toll_waycost_percentage())/100l;
break;
}
}
}
}
// now add normal way toll be maintenance
toll += (weg->get_besch()->get_wartung()*welt->get_settings().get_way_toll_waycost_percentage())/100l;
}
weg->get_besitzer()->book_toll_received( toll, get_schedule()->get_waytype() );
get_besitzer()->book_toll_paid( -toll, get_schedule()->get_waytype() );
book( -toll, CONVOI_WAYTOLL);
book( -toll, CONVOI_PROFIT);
}
get_besitzer()->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 ++;
book( 1, CONVOI_DISTANCE );
}
/* 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 && (
(sum_friction_weight == sum_gesamtgewicht && akt_speed_soll <= akt_speed && akt_speed_soll+24 >= akt_speed) ||
(sum_friction_weight > sum_gesamtgewicht && akt_speed_soll == akt_speed) )
) {
// 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 ) {
// calculate total friction and lowest speed limit
speed_limit = min( min_top_speed, front()->get_speed_limit() );
sum_gesamtgewicht = front()->get_gesamtgewicht();
sum_friction_weight = front()->get_frictionfactor() * sum_gesamtgewicht;
for( unsigned i=1; i<anz_vehikel; i++ ) {
const vehikel_t* v = fahr[i];
int total_vehicle_weight = v->get_gesamtgewicht();
sum_friction_weight += v->get_frictionfactor() * total_vehicle_weight;
sum_gesamtgewicht += total_vehicle_weight;
speed_limit = min( speed_limit, v->get_speed_limit() );
}
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];
}
distance_since_last_stop++;
sum_speed_limit += speed_to_kmh( min( min_top_speed, speed_limit ));
recalc_data_front = false;
}
akt_speed_soll = min( speed_limit, brake_speed_soll );
recalc_data = false;
}
// Prissi: more pleasant and a little more "physical" model *
// try to simulate quadratic friction
if(sum_gesamtgewicht != 0) {
/*
* 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
*/
/* but for integer, we have to use the order below and calculate actually 64*deccel, like the sum_gear_und_leistung
* 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 deccelerate 4x more => >>6 instead >>8 */
//sint32 deccel = ( ( (akt_speed*sum_friction_weight)>>6 )*(akt_speed>>2) ) / 25 + (sum_gesamtgewicht*64); // this order is needed to prevent overflows!
//sint32 deccel = (sint32)( ( (sint64)akt_speed * (sint64)sum_friction_weight * (sint64)akt_speed ) / (25ll*256ll) + sum_gesamtgewicht * 64ll) / 1000ll; // intermediate still overflows so sint64
sint32 deccel = (sint32)( ( (sint64)akt_speed * ( (sum_friction_weight * (sint64)akt_speed ) / 3125ll + 1ll) ) / 2048ll + (sum_gesamtgewicht * 64ll) / 1000ll);
// prissi: integer sucks with planes => using floats ...
// turfit: result can overflow sint32 and double so onto sint64. planes ok.
//sint32 delta_v = (sint32)( ( (double)( (akt_speed>akt_speed_soll?0l:sum_gear_und_leistung) - deccel)*(double)delta_t)/(double)sum_gesamtgewicht);
// we normalize delta_t to 1/64th and check for speed limit */
//sint32 delta_v = ( ( (akt_speed>akt_speed_soll?0l:sum_gear_und_leistung) - deccel) * delta_t)/sum_gesamtgewicht;
sint64 delta_v = ( (sint64)((akt_speed>akt_speed_soll?0l:sum_gear_und_leistung) - deccel) * (sint64)delta_t * 1000ll) / (sint64)sum_gesamtgewicht;
// 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();
}
}
int convoi_t::get_vehicle_at_length(uint16 length)
{
int current_length = 0;
for( int i=0; i<anz_vehikel; i++ ) {
current_length += fahr[i]->get_besch()->get_length();
if(length<current_length) {
return i;
}
}
return anz_vehikel;
}
// moves all vehicles of a convoi
bool convoi_t::sync_step(uint32 delta_t)
{
// still have to wait before next action?
wait_lock -= delta_t;
if(wait_lock > 0) {
return true;
}
wait_lock = 0;
switch(state) {
case INITIAL:
// jemand muß start aufrufen, damit der convoi von INITIAL
// nach ROUTING_1 geht, das kann nicht automatisch gehen
break;
case FAHRPLANEINGABE:
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]->fahre_basis(1<<YARDS_PER_VEHICLE_STEP_SHIFT);
int v_nr = get_vehicle_at_length((++steps_driven)>>4);
// stop when depot reached
if(state==INITIAL || state==ROUTING_1) {
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;
return true;
}
// now only the right numbers
for(int i=1; i<=v_nr; i++) {
fahr[i]->fahre_basis(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]->rauche();
}
}
}
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]->fahre_basis(sp_soll);
// stop when depot reached ...
if(state==INITIAL) {
break;
}
// now move the rest (so all vehikel are moving synchroniously)
for(unsigned i=1; i<anz_vehikel; i++) {
fahr[i]->fahre_basis(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]->rauche();
}
}
}
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 ma give stange effects
break;
default:
dbg->fatal("convoi_t::sync_step()", "Wrong state %d!\n", state);
break;
}
return true;
}
/**
* Berechne route von Start- zu Zielkoordinate
* @author Hanjsörg Malthaner
*/
bool convoi_t::drive_to()
{
if( anz_vehikel>0 ) {
koord3d start = fahr[0]->get_pos();
koord3d ziel = fpl->get_current_eintrag().pos;
// avoid stopping midhalt
if( start==ziel ) {
halthandle_t halt = haltestelle_t::get_halt(ziel,get_besitzer());
if( halt.is_bound() && route.is_contained(start) ) {
for( uint32 i=route.index_of(start); i<route.get_count(); i++ ) {
grund_t *gr = welt->lookup(route.position_bei(i));
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_besitzer()->bescheid_vehikel_problem( self, ziel );
}
// wait 25s before next attempt
wait_lock = 25000;
}
else {
bool route_ok = true;
const uint8 aktuell = fpl->get_aktuell();
if( fahr[0]->get_waytype() != water_wt ) {
aircraft_t *const plane = dynamic_cast<aircraft_t *>(fahr[0]);
uint32 takeoff, search, landing;
aircraft_t::flight_state plane_state;
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) ) {
fpl_target = ziel;
}
// continue route search until the destination is a station
while( is_waypoint(ziel) ) {
start = ziel;
fpl->advance();
ziel = fpl->get_current_eintrag().pos;
if( fpl->get_aktuell() == aktuell ) {
// 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_besitzer()->bescheid_vehikel_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)
looped = route.is_contained(next_segment.position_bei(1));
#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++ ) {