-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.nut
2373 lines (2003 loc) · 76.8 KB
/
connection.nut
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
//////////////////////////////////////////////////////////////////////
// //
// CLASS: Connection - a transport connection //
// //
//////////////////////////////////////////////////////////////////////
// My aim is that this class should be as general as possible and allow 2> towns, or even cargo transport
//
// As of 2011-07-25: The class handles any cargo type, but >2 towns/industries is quite likely that it doesn't work without some work
class Connection
{
clueless_instance = null;
transport_mode = null;
cargo_type = null;
// date built
date_built = null;
last_vehicle_manage = null;
// used towns and industries (arrays)
town = null;
industry = null;
// links to infrastructure and vehicles (arrays)
station = null; // station tile
depot = null;
// nodes from PairFinder. Some day perhaps town + industry could be removed as they are in the node class (arrays of Node)
node = null;
last_station_manage = null;
last_repair_route = null;
station_statistics = null; // array of pointers to StationStatistics objects for each station
max_station_usage = null;
max_station_tile_usage = null;
long_time_mean_income = 0;
last_bus_buy = null;
last_bus_sell = null;
last_airport_upgrade_fail = null;
desired_engine = null;
airport_upgrade_list = null; // list of airports (stations) to upgrade
airport_upgrade_failed = false; // set to true during upgrade if any airport failed
airport_upgrade_start = null; // when did the upgrade start?
static STATE_BUILDING = 0;
static STATE_FAILED = 1;
static STATE_ACTIVE = 2;
static STATE_CLOSED_DOWN = 10;
static STATE_CLOSING_DOWN = 11;
static STATE_SUSPENDED = 20;
static STATE_AIRPORT_UPGRADE = 30;
state = null;
state_change_date = null;
zero_production_detected_date = null;
constructor(clueless_instance) {
this.clueless_instance = clueless_instance;
this.transport_mode = TM_INVALID;
this.cargo_type = null;
this.date_built = null;
this.last_vehicle_manage = null;
this.town = [];
this.industry = [];
this.node = [];
this.station = [null, null];
this.depot = [null, null];
this.last_station_manage = null;
this.last_repair_route = null;
this.station_statistics = [];
this.max_station_usage = 0; // overall usage of the station with highest overall usage
this.max_station_tile_usage = 0; // usage of the tile with highest usage
this.long_time_mean_income = 0;
this.state_change_date = 0;
this.SetState(Connection.STATE_BUILDING);
this.last_bus_buy = null;
this.last_bus_sell = null;
this.last_airport_upgrade_fail = null;
this.desired_engine = null;
this.airport_upgrade_list = null;
this.airport_upgrade_failed = null;
this.airport_upgrade_start = null;
this.zero_production_detected_date = 0;
}
function GetName();
function SetState(newState);
function ReActivateConnection();
function SuspendConnection();
function CloseConnection();
function IsTownOnly();
function HasSmallAirport();
function GetSmallAirportCount();
function HasMagicDTRSStops();
function GetTotalPoputaltion();
function GetTotalDistance(); // only implemented for 2 towns
function ManageState()
function ManageStations()
function ManageVehicles();
function SendVehicleForSelling(vehicle_id);
function GetMinMaxRatingWaiting();
function ManageAirports();
function CheckForAirportUpgrade();
function TryUpgradeAirports();
function FindEngineModelToBuy();
function BuyVehicles(num_vehicles, engine_id);
function NumVehiclesToBuy(connection);
function GetDepotServiceFlag();
function GetVehicles();
function GetBrokenVehicles(); // Gets broken vehicles that stops at any of the stations
// Change order functions
function FullLoadAtStations(enable_full_load);
function StopInDepots(stop_in_depots);
function SkipAllVehiclesToClosestDepot();
function RepairRoadConnection();
// Engine type management
function FindNewDesiredEngineType();
function MassUpgradeVehicles();
static function IsVehicleToldToUpgrade(vehicle_id);
static function GetVehicleUpgradeToEngine(vehicle_id);
}
function Connection::GetName()
{
// Quick version if the connection is okay.
if(node.len() == 2 && node[0] != null && node[1] != null)
return node[0].GetName() + " - " + node[1].GetName() + " (" + TransportModeToString(transport_mode) + ")";
// If one or more node is broken:
return "[broken connection]";
}
function Connection::SetState(newState)
{
this.state = newState;
this.state_change_date = AIDate.GetCurrentDate();
if(this.station != null)
{
foreach(stn in this.station)
{
if(stn != null)
Helper.SetSign(Tile.GetTileRelative(AIStation.GetLocation(AIStation.GetStationID(stn)), 1, 1), "state:" + this.state);
}
}
}
function Connection::ReActivateConnection()
{
Log.Info("ReActivateConnection " + node[0].GetName() + " - " + node[1].GetName(), Log.LVL_INFO);
// Change the depot orders to service at depots and start all vehicles
local vehicle_list = this.GetVehicles();
if(vehicle_list.IsEmpty())
{
Log.Warning("ReActivateConnection fails because connection " + node[0].GetName() + " - " + node[1].GetName() + " do not have any vehicles.", Log.LVL_INFO);
return false;
}
// Change the depot orders to service at depots (but don't stop in depot)
local veh_id = vehicle_list.Begin();
for(local i_order = 0; i_order < AIOrder.GetOrderCount(veh_id); ++i_order)
{
if(AIOrder.IsGotoDepotOrder(veh_id, i_order))
{
// Always go to depot if breakdowns are "normal", otherwise only go if needed
local service_flag = this.GetDepotServiceFlag();
local non_stop_flag = this.transport_mode == TM_ROAD || this.transport_mode == TM_RAIL? AIOrder.OF_NON_STOP_INTERMEDIATE : 0;
AIOrder.SetOrderFlags(veh_id, i_order, non_stop_flag | service_flag);
}
}
// Start all vehicles that are stoped in depot
foreach(vehicle_id, _ in vehicle_list)
{
if(AIVehicle.GetState(vehicle_id) == AIVehicle.VS_IN_DEPOT)
{
Data.StoreInVehicleName(vehicle_id, "active");
AIVehicle.StartStopVehicle(vehicle_id);
}
}
this.SetState(Connection.STATE_ACTIVE);
return true;
}
function Connection::SuspendConnection()
{
Log.Info("SuspendConnection " + node[0].GetName() + " - " + node[1].GetName(), Log.LVL_INFO);
local vehicle_list = this.GetVehicles();
if(vehicle_list.IsEmpty())
{
Log.Warning("SuspendConnection fails because connection " + node[0].GetName() + " - " + node[1].GetName() + " do not have any vehicles.", Log.LVL_INFO);
return false;
}
if(!this.StopInDepots(true))
return false;
foreach(vehicle_id, _ in vehicle_list)
{
// Store state in vehicle so they won't be sold
Data.StoreInVehicleName(vehicle_id, "suspended");
}
// Make sure vehicles that load at stations skip to depot instead of potentially forever waiting for full load
SkipAllVehiclesToClosestDepot();
this.SetState(Connection.STATE_SUSPENDED);
return true;
}
function Connection::CloseConnection()
{
Log.Info("CloseConnection " + node[0].GetName() + " - " + node[1].GetName(), Log.LVL_INFO);
if(this.transport_mode == TM_AIR)
{
AIController.Break("close air connection");
}
if(this.state == Connection.STATE_CLOSING_DOWN || this.state == Connection.STATE_CLOSED_DOWN || this.state == Connection.STATE_FAILED)
{
Log.Warning("CloseConnection fails because the current state ( " + this.state + " ) of the connection does not allow initiating the closing down process.");
return false;
}
// Send all vehicles to depot for selling and set state STATE_CLOSING_DOWN
this.SetState(Connection.STATE_CLOSING_DOWN);
local vehicle_list = this.GetVehicles();
if(vehicle_list.IsEmpty())
{
return true;
}
// Change orders so that vehicles will stay at the depots when they go there.
// By doing like this instead of calling SendVehicleForSelling for all vehicles, they will keep the stations in the orders
// so that it is possible to query the stations to see if all vehicles has been sold or not.
if(!this.StopInDepots(true))
return false;
foreach(vehicle_id, _ in vehicle_list)
{
// Store state in vehicles
Data.StoreInVehicleName(vehicle_id, "close conn");
}
// Make sure vehicles that load at stations skip to depot instead of potentially forever waiting for full load
SkipAllVehiclesToClosestDepot();
return true;
}
function Connection::IsTownOnly()
{
foreach(n in this.node)
{
// Return false if there is a non-town node
if(!n.IsTown()) return false;
}
// otherwise true
return true;
}
function Connection::HasSmallAirport()
{
if(this.transport_mode != TM_AIR)
return false;
foreach(station_tile in this.station)
{
if(station_tile == null) continue;
if(Airport.IsSmallAirport(AIStation.GetStationID(station_tile)))
return true;
}
return false;
}
function Connection::GetSmallAirportCount()
{
if(this.transport_mode != TM_AIR)
return 0;
local count = 0;
foreach(station_tile in this.station)
{
if(station_tile == null) continue;
if(Airport.IsSmallAirport(AIStation.GetStationID(station_tile)))
++count;
}
return count;
}
function Connection::HasMagicDTRSStops()
{
if(this.transport_mode != TM_ROAD)
return false;
foreach(station_tile in this.station)
{
if(AIRoad.IsDriveThroughRoadStationTile(station_tile))
return true;
}
return false;
}
function Connection::GetTotalPoputaltion()
{
local val = null;
local pop = 0;
foreach(val in town)
{
if(val != null)
{
pop += this.AITown().GetPopulation(val);
}
}
return pop;
}
function Connection::GetTotalDistance()
{
if(node.len() != 2)
return 0;
return AIMap.DistanceManhattan( this.node[0].GetLocation(), this.node[1].GetLocation() );
}
function Connection::FindEngineModelToBuy()
{
local has_small_airport = this.HasSmallAirport();
local allow_articulated_rvs = this.HasMagicDTRSStops();
local min_range = -1;
if(this.transport_mode == TM_AIR)
{
min_range = AIOrder.GetOrderDistance(AIVehicle.VT_AIR, this.station[0], this.station[1]);
}
return Strategy.FindEngineModelToBuy(this.cargo_type, TransportModeToVehicleType(this.transport_mode), has_small_airport, allow_articulated_rvs, min_range);
}
function Connection::BuyVehicles(num_vehicles, engine_id)
{
if(station.len() != 2 || this.station[0] == null || this.station[1] == null)
{
Log.Warning("BuyVehicles: wrong number of stations", Log.LVL_INFO);
return false;
}
if(depot.len() != 2 || this.depot[0] == null || this.depot[1] == null)
{
Log.Warning("BuyVehicles: wrong number of depots", Log.LVL_INFO);
return false;
}
if(num_vehicles <= 0)
{
Log.Warning("BuyVehicles: Asked to buy zero vehicles", Log.LVL_INFO);
return false;
}
// Don't buy more vehicles than allowed
num_vehicles = Helper.Min(num_vehicles, Vehicle.GetVehiclesLeft(AIEngine.GetVehicleType(engine_id)));
if(num_vehicles <= 0)
{
Log.Warning("BuyVehicles: Vehicle limit doesn't allow any new vehicles", Log.LVL_SUB_DECISIONS);
return false;
}
local min_reliability = 85;
local new_bus;
local i;
local exec = AIExecMode();
local share_orders_with = -1;
if(engine_id == null || !AIEngine.IsBuildable(engine_id))
{
Log.Warning("BuyVehicles: failed to find a bus/truck to build", Log.LVL_INFO);
return false;
}
Log.Info("BuyVehicles: engine name: " + AIEngine.GetName(engine_id), Log.LVL_SUB_DECISIONS);
local new_buses = [];
// Buy buses
for(i = 0; i < num_vehicles; ++i)
{
new_bus = AIVehicle.BuildVehicle(depot[i%2], engine_id);
if(AIVehicle.IsValidVehicle(new_bus))
{
if(AIVehicle.RefitVehicle(new_bus, this.cargo_type))
{
Log.Info("I built a vehicle", Log.LVL_DEBUG);
new_buses.append(new_bus);
}
else
{
Log.Warning("Failed to refit vehicle because " + AIError.GetLastErrorString(), Log.LVL_INFO);
// Sell the vehicle as we couldn't refit it
AIVehicle.SellVehicle(new_bus);
new_bus = -1;
}
// Store current state in vehicle name
if(this.state == Connection.STATE_SUSPENDED)
Data.StoreInVehicleName(new_bus, "suspended");
else if(this.state == Connection.STATE_ACTIVE)
Data.StoreInVehicleName(new_bus, "active");
else if(this.state == Connection.STATE_CLOSING_DOWN) // There is not really a reason to buy vehicles in this state!
Data.StoreInVehicleName(new_bus, "close conn");
else if(this.state == Connection.STATE_BUILDING)
{ }
else if(this.state == null) // build state
Data.StoreInVehicleName(new_bus, "active");
else
{
Log.Warning("Built vehicle while in state " + this.state, Log.LVL_INFO);
}
}
if(!AIVehicle.IsValidVehicle(new_bus)) // if failed to buy last vehicle
{
if(i == 0)
{
local dep = depot[i%2];
local x = AIMap.GetTileX(dep);
local y = AIMap.GetTileY(dep);
Log.Info("Build vehicle error string: " + AIError.GetLastErrorString(), Log.LVL_INFO);
Log.Warning("Depot is " + dep + ", location: " + x + ", " + y, Log.LVL_INFO);
if(!AIMap.IsValidTile(dep))
Log.Warning("Depot is invalid tile!", Log.LVL_INFO);
if(!AIEngine.IsValidEngine(engine_id))
Log.Warning("Invalid engine!", Log.LVL_INFO);
if(!AIEngine.IsBuildable(engine_id))
Log.Warning("Engine not buildable!", Log.LVL_INFO);
Log.Warning("Failed to buy bus/truck", Log.LVL_INFO);
return false; // if no bus have been built, return false
}
else
{
num_vehicles = i;
break;
}
}
// See if there is existing vehicles to share orders with
// (vehicles not in depot could have been destroyed by a train or an UFO so don't rely
// on old information -> check every time that share_orders_with is a valid vehicle)
AIController.Sleep(1);
if(share_orders_with == -1 || !AIVehicle.IsValidVehicle(share_orders_with))
{
local existing_vehicles = GetVehicles();
local num_old_vehicles = existing_vehicles.Count();
if(!existing_vehicles.IsEmpty())
share_orders_with = existing_vehicles.Begin();
}
// Share orders of existing vehicle or assign new orders
if(AIVehicle.IsValidVehicle(share_orders_with))
{
AIOrder.ShareOrders(new_bus, share_orders_with);
}
else
{
// Always go to depot if breakdowns are "normal", otherwise only go if needed
local service_flag = (this.transport_mode == TM_ROAD || this.transport_mode == TM_RAIL? AIOrder.OF_NON_STOP_INTERMEDIATE : 0) | this.GetDepotServiceFlag();
local station_flag = this.transport_mode == TM_ROAD || this.transport_mode == TM_RAIL? AIOrder.OF_NON_STOP_INTERMEDIATE : AIOrder.OF_NONE;
AIOrder.AppendOrder(new_bus, depot[0], service_flag);
AIOrder.AppendOrder(new_bus, station[0], station_flag);
AIOrder.AppendOrder(new_bus, depot[1], service_flag);
AIOrder.AppendOrder(new_bus, station[1], station_flag);
share_orders_with = new_bus;
}
}
for(i = 0; i < new_buses.len(); ++i)
{
if(i%2 == 0)
AIOrder.SkipToOrder(new_buses[i], 1);
else
AIOrder.SkipToOrder(new_buses[i], 3);
}
for(i = 0; i < new_buses.len(); ++i)
{
if(i%2 == 1)
AIController.Sleep(20);
// Don't start new vehicles if connection is suspended
if(this.state != Connection.STATE_SUSPENDED)
AIVehicle.StartStopVehicle(new_buses[i]);
else
Log.Info("Don't start new vehicle (" + AIVehicle.GetName(new_buses[i]) + " because connection is suspended", Log.LVL_SUB_DECISIONS);
}
this.last_bus_buy = AIDate.GetCurrentDate();
Log.Info("Built bus => return true", Log.LVL_DEBUG);
return true;
}
function Connection::NumVehiclesToBuy(engine_id)
{
local distance = GetTotalDistance().tofloat();
local speed = AIEngine.GetMaxSpeed(engine_id);
local travel_time = 5 + Engine.GetFullSpeedTraveltime(engine_id, distance);
local capacity = AIEngine.GetCapacity(engine_id);
Log.Info("NumVehiclesToBuy(): distance: " + distance, Log.LVL_SUB_DECISIONS);
Log.Info("NumVehiclesToBuy(): travel time: " + travel_time, Log.LVL_SUB_DECISIONS);
Log.Info("NumVehiclesToBuy(): capacity: " + capacity + " cargo_type: " + cargo_type + " engine_id: " + engine_id, Log.LVL_SUB_DECISIONS);
if(this.IsTownOnly())
{
// Town only connections
local population = GetTotalPoputaltion().tofloat();
Log.Info("NumVehiclesToBuy(): total town population: " + population, Log.LVL_SUB_DECISIONS);
local num_bus = 1 + max(0, (Helper.Min(1400, population - 200) / capacity / 15).tointeger());
local extra = distance/capacity/3;
num_bus += extra;
Log.Info("NumVehiclesToBuy(): extra: " + extra, Log.LVL_SUB_DECISIONS);
num_bus = num_bus.tointeger();
Log.Info("NumVehiclesToBuy(): Buy " + num_bus + " vehicles", Log.LVL_SUB_DECISIONS);
return num_bus;
}
else
{
// All other connections
local max_cargo_available = Helper.Max(this.node[0].GetCargoAvailability(), this.node[1].GetCargoAvailability());
Log.Info("NumVehiclesToBuy(): cargo availability: " + max_cargo_available, Log.LVL_SUB_DECISIONS);
// * 70 / 100 => assume 90% station rating
local tor_month_to_days = 30;
local tor_production = max_cargo_available * 70 / 100 * (travel_time * 2) / tor_month_to_days;
local num_veh = 2 + (tor_production / capacity).tointeger();
// Old num_veh code:
//local num_veh = (travel_time * capacity / 83).tointeger();
Log.Info("NumVehiclesToBuy(): Buy " + num_veh + " vehicles", Log.LVL_SUB_DECISIONS);
return num_veh;
}
}
function Connection::GetDepotServiceFlag()
{
if(AIGameSettings.GetValue("vehicle_breakdowns") != 2 || // if breakdowns is enabled
HasMagicDTRSStops())
{
return 0; // Always visit the depots
}
else
{
return AIOrder.OF_SERVICE_IF_NEEDED;
}
}
function Connection::ManageState()
{
Log.Info("Manage connection state - state: " + this.state + " - " + node[0].GetName() + " - " + node[1].GetName(), Log.LVL_SUB_DECISIONS);
// Check if there is at least one working transport direction. Working in this case is that
// one end produces the cargo and another end accpts it.
if(this.state != Connection.STATE_CLOSING_DOWN && this.state != Connection.STATE_SUSPENDED && this.state != Connection.STATE_CLOSED_DOWN)
{
local accept0 = Station.IsCargoAccepted(this.station_statistics[0].station_id, this.node[0].cargo_id);
local accept1 = Station.IsCargoAccepted(this.station_statistics[1].station_id, this.node[1].cargo_id);
local has_prod_accept_pair = (this.node[0].IsCargoProduced() && accept1) ||
(this.node[1].IsCargoProduced() && accept0);
// TODO: Read OpenTTD Source and see if SkipToOrder works if vehicles already at order 0 and we want to skip to that order so they leave the station
if(!has_prod_accept_pair)
{
// One industry has closed down or town station has lost accept/produce status
// -> CloseConnection
Log.Info("Connection do no longer has at least one producer-accepter pair -> close connection", Log.LVL_DEBUG);
this.CloseConnection();
return;
}
// Check if any of the (industry) nodes has disappeared. That is if the industry is gone or has moved elsewhere.
if(this.node[0].HasNodeDissapeared() || this.node[1].HasNodeDissapeared())
{
Log.Info("One or more of the nodes (town/industry) of connection has disappeared -> close connection", Log.LVL_DEBUG);
this.CloseConnection();
return;
}
}
// Go through the possible states
if(this.state == Connection.STATE_ACTIVE)
{
if(this.GetVehicles().IsEmpty())
{
// Close connection if it does not have any vehicles
this.CloseConnection();
}
else
// Production checks
if(!this.IsTownOnly())
{
// Check if one of the producing industries has zero production
local zero_raw_production = false;
local zero_secondary_production = false;
local max_production = 0;
foreach(node in this.node)
{
local node_production = node.GetLastMonthProduction();
if(node.IsIndustry() &&
node.IsCargoProduced() &&
node_production < 1)
{
if(AIIndustryType.IsRawIndustry(AIIndustry.GetIndustryType(node.industry_id)))
zero_raw_production = true;
else
zero_secondary_production = true;
}
// Keep track of the max production
if(node_production > max_production)
max_production = node_production;
}
// If there is a secondary industry with zero production, start by suspending
// the connection and see if it will start producing again. The vehicles of
// this connection could be blocking the trucks with raw materials.
if(max_production > 0)
{
if(zero_secondary_production || zero_raw_production)
{
// Dual way connection where one node has zero production
// Update full-load orders
// The function will only full load at the end with highest production so that will solve the issue
this.FullLoadAtStations(true);
}
// Unset the date when zero production was detected
this.zero_production_detected_date = 0;
}
else
{
// Single or double way connection with all nodes at zero production
if(zero_secondary_production)
{
// Set the date when zero production was detected if not set
if(this.zero_production_detected_date == 0)
{
this.zero_production_detected_date = AIDate.GetCurrentDate();
}
// If there have been zero production for more than 90 days, close the connection
else if(this.zero_production_detected_date + 90 < AIDate.GetCurrentDate())
{
this.CloseConnection();
}
else
{
// One of the producing nodes is a non-raw node -> suspend connection for a while
// and hope that the industry will start produce cargo again
// However, if the stations are not much in use, it is better to keep the connection
// active to not cause bad station ratings.
local check = false;
switch(this.transport_mode)
{
case TM_ROAD:
check = this.max_station_usage > 135 || this.max_station_tile_usage > 180;
break;
case TM_RAIL:
check = this.max_station_usage > 135; // tweak
break;
default:
check = false;
}
if(check)
{
this.SuspendConnection();
}
}
}
else if(zero_raw_production)
{
// Only raw industries -> No hope for increased production again
this.CloseConnection();
}
}
}
if(this.node[0].HasNodeDissapeared() || this.node[1].HasNodeDissapeared())
{
Log.Info("A node has dissapeared from connection " + this.GetName() + " => close it down", Log.LVL_INFO);
this.CloseConnection();
return;
}
}
else if(this.state == Connection.STATE_SUSPENDED)
{
local now = AIDate.GetCurrentDate();
local suspended_time = now - this.state_change_date;
Log.Info("Connection has been suspended for " + suspended_time + " days");
// Check if the connection has been suspended for at least 35 days
if(suspended_time > 35)
{
// Check if the connection should be re-activated or closed down
foreach(node in this.node)
{
if(node.GetLastMonthProduction() > 0)
{
this.ReActivateConnection();
break;
}
}
// If the connection was not re-activated within 90 days, close it down
if(this.state == Connection.STATE_SUSPENDED && suspended_time > 90)
{
this.CloseConnection();
}
}
}
else if(this.state == Connection.STATE_CLOSING_DOWN)
{
if(this.transport_mode == TM_AIR)
{
AIController.Break("close air connection");
}
local vehicle_list = this.GetVehicles();
// Sell vehicles in depot
foreach(vehicle_id, _ in vehicle_list)
{
if(AIVehicle.GetState(vehicle_id) == AIVehicle.VS_IN_DEPOT)
{
AIVehicle.SellVehicle(vehicle_id);
}
}
// Refresh the vehicle list
vehicle_list = this.GetVehicles();
if(vehicle_list.IsEmpty())
{
// All vehicles has been sold
Log.Info("close con: All vehicles have been sold.", Log.LVL_DEBUG);
local front_tiles = AIList();
// Demolish stations
foreach(station_tile in this.station)
{
if(station_tile == null) continue;
Helper.SetSign(station_tile, "close conn");
local station_id = AIStation.GetStationID(station_tile);
// Remember the front tiles for later road removal
if(this.transport_mode == TM_ROAD)
front_tiles.AddList(Station.GetRoadFrontTiles(station_id));
// Demolish station
Station.DemolishStation(station_id);
}
// Demolish depots
foreach(depot in this.depot)
{
if(depot == null) continue;
Helper.SetSign(depot, "close conn");
local front = null;
if(this.transport_mode == TM_ROAD)
{
front = AIRoad.GetRoadDepotFrontTile(depot);
// Remember the front tile for later road removal
front_tiles.AddItem(front, 0);
}
// Demolish depot
if(AIRoad.IsRoadDepotTile(depot) && !AITile.DemolishTile(depot))
{
if(AIError.GetLastError() == AIError.ERR_VEHICLE_IN_THE_WAY)
{
local sell_failed = false;
local vehicles_in_depot = Vehicle.GetVehiclesAtTile(depot);
foreach(veh_in_depot, _ in vehicles_in_depot)
{
if(!AIVehicle.IsStoppedInDepot(veh_in_depot))
{
// The vehicle is not stoped in depot
// -> Try to stop it and see if it is now stopped in the depot
AIVehicle.StartStopVehicle(veh_in_depot);
if(!AIVehicle.IsStoppedInDepot(veh_in_depot))
{
// The vehicle is stoped, but not in the depot
// -> Start it again
AIVehicle.StartStopVehicle(veh_in_depot);
sell_failed = true;
continue;
}
}
AIVehicle.SellVehicle(veh_in_depot);
}
if(sell_failed)
{
Log.Warning("Error while removing depot for closing down connection: There was a vehicle in the way half way on the way in or out of the depot -> could not sell it", Log.LVL_INFO);
Log.Info("-> abort closing connection for now", Log.LVL_INFO);
// Abort closing down for a while
return;
}
// Now the depot should be empty of vehicles
if(!AITile.DemolishTile(depot))
{
Log.Warning("Error: Failed to demolish depot even after having tried to sell vehicles that are in the way", Log.LVL_INFO);
Log.Info("-> abort closing connection for now", Log.LVL_INFO);
return;
}
}
else
{
Log.Warning("Could not demolish depot because of " + AIError.GetLastErrorString());
Log.Info("-> abort closing connection for now", Log.LVL_INFO);
return;
}
}
if(this.transport_mode == TM_ROAD)
AIRoad.RemoveRoad(front, depot);
}
// debug signs
foreach(tile, _ in front_tiles)
{
Helper.SetSign(tile, "front");
}
// Remove road from all front tiles
if(this.transport_mode == TM_ROAD)
{
foreach(tile, _ in front_tiles)
{
Road.RemoveRoadUpToRoadCrossing(tile);
}
}
Log.Info("Change state to STATE_CLOSED_DOWN");
this.SetState(Connection.STATE_CLOSED_DOWN);
} else {
// Make sure vehicles stop in depot.
this.StopInDepots(true);
}
}
else if(this.state == Connection.STATE_AIRPORT_UPGRADE)
{
// Try to get further in the upgrade process
Log.Info("Manage state - try to continue upgrading the airports", Log.LVL_SUB_DECISIONS);
this.TryUpgradeAirports();
}
}
function Connection::ManageStations()
{
if(this.state != Connection.STATE_ACTIVE)
return;
if(this.station[0] == null || this.station[1] == null)
{
this.CloseConnection();
return;
}
// Don't manage too often
local now = AIDate.GetCurrentDate();
if(this.last_station_manage != null && now - this.last_station_manage < 5)
return;
this.last_station_manage = now;
Log.Info("Manage Stations: " + this.GetName(), Log.LVL_INFO);
// Update station statistics
if(this.transport_mode != TM_WATER)
{
local max_station_usage = 0;
local max_station_tile_usage = 0;
for(local i = 0; i < this.station.len(); ++i)
{
local station_tile = this.station[i];
local station_statistics = this.station_statistics[i];
// Close connection if one of the stations are invalid
if(!AIStation.IsValidStation(AIStation.GetStationID(station_tile)))
{
Log.Warning("An invalid station was detected -> Close connection", Log.LVL_INFO);
CloseConnection();
return;
}
station_statistics.ReadStatisticsData();
local usage = null;
local max_tile_usage = null;
switch(this.transport_mode)
{
case TM_ROAD:
usage = Helper.Max(station_statistics.usage.bus.percent_usage, station_statistics.usage.truck.percent_usage);
max_tile_usage = Helper.Max(station_statistics.usage.bus.percent_usage_max_tile, station_statistics.usage.truck.percent_usage_max_tile);
break;
case TM_AIR:
usage = station_statistics.usage.aircraft.percent_usage;
break;
case TM_RAIL:
usage = station_statistics.usage.train.percent_usage;
break;
}
if(usage > max_station_usage)
max_station_usage = usage;
if(this.transport_mode == TM_ROAD && max_tile_usage > max_station_tile_usage)
max_station_tile_usage = max_tile_usage;
}
this.max_station_usage = max_station_usage;
this.max_station_tile_usage = max_station_tile_usage;
}
// road specific station management
if(this.transport_mode == TM_AIR)
{
this.ManageAirports();
if(this.station[0] == null || this.station[1] == null) return; // may happen if airport upgrade fails with a broken connection
}
else if(this.transport_mode == TM_ROAD)
{
// Check that all station parts are connected to road