-
Notifications
You must be signed in to change notification settings - Fork 81
/
ActivityFile.cs
1446 lines (1234 loc) · 65.2 KB
/
ActivityFile.cs
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
// COPYRIGHT 2009, 2010, 2011, 2013, 2014, 2015 by the Open Rails project.
//
// This file is part of Open Rails.
//
// Open Rails is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Open Rails is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Open Rails. If not, see <http://www.gnu.org/licenses/>.
//EBNF
//Usage follows http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form
//Usage Notation
//================ ========
//definition =
//concatenation ,
//termination ;
//alternation |
//option [ ... ]
//repetition { ... }
//grouping ( ... )
//terminal string " ... "
//terminal string ' ... '
//comment (* ... *)
//special sequence ? ... ?
//exception -
//(* MSTS Activity syntax in EBNF *)
//(* Note inconsistent use of "_" in names *)
//(* Note very similar names for different elements: ID v UiD, WagonsList v Wagon_List v Wagon, Train_Config v TrainCfg *)
//(* Note some percentages as integers 0-100 and some as float, e.g. 0.75 *)
//(* Note some times as 3*Integer for hr, min, sec and some as Integer seconds since some reference. *)
//(* As with many things Microsoft, text containing spaces must be enclosed in "" and text with no spaces needs no delimiter. *)
//Tr_Activity =
// "(", Serial, Tr_Activity_Header, Tr_Activity_File, ")" ;
// Serial = "Serial", "(", Integer, ")" ;
// Tr_Activity_Header = "Tr_Activity_Header",
// "(", *[ RouteID | Name | Description | Briefing | CompleteActivity
// | Type | Mode | StartTime | Season | Weather | PathID | StartingSpeed | Duration | Difficulty
// | Animals | Workers | FuelWater | FuelCoal | FuelDiesel ] ")" ;
// (* 1 or more options. Sequence is probably not significant.
// No information about which options are required or checking for duplicates.
// *)
// RouteID = "RouteID", "(", Text, ")" ; (* file name *)
// Name = "Name", "(", Text, ")" ;
// Description = "Description", "(", Text, ")" ;
// Briefing = "Briefing", "(", ParagraphText, ")" ;
// ParagraphText = Text, *( "+", Text ) ;
// CompleteActivity = "CompleteActivity", "(", Integer, ")" ; (* 1 for true (to be checked) *)
// Type = "Type", "(", Integer, ")" ; (* 0 (default) for ??? (to be checked) *)
// Mode = "Mode", "(", Integer, ")" ; (* 2 (default) for ??? (to be checked) *)
// StartTime = "StartTime", "(", 3*Integer, ")" ; (* Hour, Minute, Second (default is 10am) *)
// Season = "Season", "(", Integer, ")" ; (* Spring=0, Summer (default), Autumn, Winter *)
// Weather = "Weather", "(", Integer, ")" ; (* Clear=0 (default), Snow, Rain *)
// PathID = "PathID", "(", Text , ")" ;
// StartingSpeed = "StartingSpeed", "(", Integer, ")" ; (* 0 (default) for meters/second *) (* Why integer? *)
// Duration = "Duration", "(", 2*Integer, ")" ; (* Hour , Minute (default is 1 hour) *)
// Difficulty = "Difficulty", "(", Integer, ")" ; (* Easy=0 (default), Medium, Hard *)
// Animals = "Animals", "(", Integer, ")" ; (* 0-100 for % (default is 100) *)
// Workers = "Workers", "(", Integer, ")" ; (* 0-100 for % (default is 0) *)
// FuelWater = "FuelWater", "(", Integer, ")"; (* 0-100 for % (default is 100) *)
// FuelCoal = "FuelCoal", "(", Integer, ")"; (* 0-100 for % (default is 100) *)
// FuelDiesel = "FuelDiesel", "(", Integer, ")"; (* 0-100 for % (default is 100) *)
// Tr_Activity_File = "Tr_Activity_File",
// "(", *[ Player_Service_Definition | NextServiceUID | NextActivityObjectUID
// | Traffic_Definition | Events | ActivityObjects | ActivityFailedSignals | PlatformNumPassengersWaiting | ActivityRestrictedSpeedZones ] ")" ;
// Player_Service_Definition = "Player_Service_Definition", (* Text is linked to PathID somehow. *)
// "(", Text, [ Player_Traffic_Definition | UiD | *Player_Service_Item ], ")" ; (* Code suggests just one Player_Traffic_Definition *)
// Player_Traffic_Definition = "Player_Traffic_Definition",
// "(", Integer, *( Player_Traffic_Item ), ")" ;
// Player_Traffic_Item = (* Note lack of separator between Player_Traffic_Items.
// For simplicity, parser creates a new object whenever PlatformStartID is parsed. *)
// *[ "ArrivalTime", "(", Integer, ")"
// | "DepartTime", "(", Integer, ")"
// | "SkipCount", "(", Integer, ")"
// | "DistanceDownPath", "(", Float, ")" ],
// "PlatformStartID", "(", Integer, ")" ;
// UiD = "UiD", "(", Integer, ")" ;
// Player_Service_Item = (* Note lack of separator between Player_Service_Items *)
// For simplicity, parser creates a new object whenever PlatformStartID is parsed. *)
// *[ "Efficiency", "(", Float, ")" (* e.g. 0.75 for 75% efficient? *)
// | "SkipCount", "(", Integer, ")"
// | "DistanceDownPath", "(", Float, ")" ],
// "PlatformStartID", "(", Integer, ")" ;
// NextServiceUID = "NextServiceUID", "(", Integer, ")" ;
// NextActivityObjectUID = "NextActivityObjectUID", "(", Integer, ")" ;
// Traffic_Definition = "Traffic_Definition", "(", Text, *Service_Definition, ")" ;
// Service_Definition = "Service_Definition",
// "(", Text, Integer, UiD, *Player_Service_Item, ")" ; (* Integer is time in seconds *)
// Events = "Events",
// "(", *[ EventCategoryLocation | EventCategoryAction | EventCategoryTime ], ")" ; (* CategoryTime *)
// EventCategoryLocation = "EventCategoryLocation",
// "(", *[ EventTypeLocation | ID | Activation_Level | Outcomes
// | Name | Location | TriggerOnStop ], ")" ; (* ID and Name defined above *)
// EventTypeLocation = "EventTypeLocation", "(", ")" ;
// ID = "ID", "(", Integer, ")" ;
// Activation_Level = "Activation_Level", "(", Integer, ")" ;
// Outcomes = "Outcomes",
// "(", *[ ActivitySuccess | ActivityFail | ActivateEvent | RestoreActLevel | DecActLevel | IncActLevel | DisplayMessage ], ")" ;
// ActivitySuccess = "ActivitySuccess", "(", ")" ; (* No text parameter *)
// ActivityFail = "ActivityFail", "(", Text, ")" ;
// ActivateEvent = "ActivateEvent", "(", Integer, ")" ;
// RestoreActLevel = "RestoreActLevel", "(", Integer, ")" ;
// DecActLevel = "DecActLevel", "(", Integer, ")" ;
// IncActLevel = "IncActLevel", "(", Integer, ")" ; (* Some MSTS samples have more than a single IncActLevel *)
// DisplayMessage = "DisplayMessage", "(", Text, ")" ;
// Location = "Location", "(", 5*Integer, ")" ;
// TriggerOnStop = "TriggerOnStop", "(", Integer, ")" ; (* 0 for ?? *)
// TextToDisplayOnCompletionIfTriggered = "TextToDisplayOnCompletionIfTriggered", "(", ParagraphText, ")" ;
// TextToDisplayOnCompletionIfNotTriggered = "TextToDisplayOnCompletionIfNotTriggered", "(", ParagraphText, ")" ;
// EventCategoryAction = "EventCategoryAction",
// "(", *[ EventType | ID | Activation_Level
// | Outcomes | Reversable_Event | Name | Wagon_List | SidingItem | StationStop | Speed ] ; (* ID, Activation_Level, Outcomes and Name defined above *)
// EventType =
// [ EventTypeAllStops | EventTypeAssembleTrain
// | EventTypeAssembleTrainAtLocation | EventTypeDropOffWagonsAtLocation
// | EventTypePickUpPassengers | EventTypePickUpWagons
// | EventTypeReachSpeed ] ;
// EventTypeAllStops = "EventTypeAllStops", "(", ")" ;
// EventTypeAssembleTrain = "EventTypeAssembleTrain", "(", ")" ;
// EventTypeAssembleTrainAtLocation = "EventTypeAssembleTrainAtLocation", "(", ")" ;
// EventTypeDropOffWagonsAtLocation = "EventTypeDropOffWagonsAtLocation", "(", ")" ;
// EventTypePickUpPassengers = "EventTypePickUpPassengers", "(", ")" ;
// EventTypePickUpWagons = "EventTypePickUpWagons", "(", ")" ;
// EventTypeReachSpeed = "EventTypeReachSpeed", "(", ")" ;
// Reversable_Event = [ "Reversable_Event" | "Reversible_Event" ], (* Reversable is not listed at www.learnersdictionary.com *)
// "(", ")" ;
// SidingItem = "(", Integer, ")" ;
// Wagon_List = "Wagon_List", "(", *WagonListItem, ")" ;
// WagonListItem = (* Description omitted from PickUpWagons and sometimes from DropOffWagonsAtLocation *)
// UiD, SidingItem, [ "Description", "(", Text, ")" ] ; (" MSTS uses SidingItem inside the Wagon_List and also at the same level *)
// StationStop =
// Speed = "(", Integer, ")" ;
// EventCategoryTime = "EventCategoryTime", "(", (* single instance of each alternative *)
// [ EventTypeTime | ID | Activation_Level | Outcomes | TextToDisplayOnCompletionIfTriggered
// | TextToDisplayOnCompletionIfNotTriggered | Name | Time ], ")" ; (* Outcomes may have empty parameters *)
// EventTypeTime = "EventTypeTime", "(", ")" ;
// Time = "Time", "(", Integer, ")" ;
// ActivityObjects = "ActivityObjects", "(", *ActivityObject, ")" ;
// ActivityObject = "ActivityObject",
// "(", *[ ObjectType | Train_Config | Direction | ID | Tile ], ")" ; (* ID defined above *)
// ObjectType = "ObjectType",
// "(", [ "WagonsList" | ?? ], ")" ;
// Train_Config = "Train_Config", "(", TrainCfg, ")" ;
// TrainCfg = "TrainCfg",
// "(", [ Name | Serial | MaxVelocity | NextWagonUID | Durability | Wagon | Engine ], ")" ;
// Serial = "Serial", "(", Integer, ")" ;
// MaxVelocity = "MaxVelocity", "(", 2*Float, ")" ;
// NextWagonUID = "NextWagonUID", "(", Integer, ")" ;
// Durability = "Durability", "(", Float, ")" ;
// Wagon = "Wagon",
// "(", *[ WagonData | UiD ], ")" ; (* UiD defined above *)
// WagonData = "WagonData", "(", 2*Text, ")" ;
// Engine = "Engine", "(", *[ UiD | EngineData ], ")" ; (* UiD defined above *)
// EngineData = "EngineData",
// "(", 2*Text, ")" ;
// Direction = "Direction", "(", Integer, ")" ; (* 0 for ??, 1 for ?? *)
// Tile = "Tile", "(", 2*Integer, 2*Float, ")" ;
// ActivityFailedSignals = "ActivityFailedSignals", "(", *ActivityFailedSignal, ")" ;
// ActivityFailedSignal = "ActivityFailedSignal", "(", Integer, ")" ;
// PlatformNumPassengersWaiting = "PlatformNumPassengersWaiting", "(", *PlatformData, ")" ;
// PlatformData = "PlatformData", "(", 2*Integer, ")" ;
// ActivityRestrictedSpeedZones = "ActivityRestrictedSpeedZones", "(", *ActivityRestrictedSpeedZone, ")" ;
// ActivityRestrictedSpeedZone = "ActivityRestrictedSpeedZone",
// "(", StartPosition, EndPosition, ")" ;
// StartPosition = "StartPosition, "(", 4*Integer, ")" ;
// EndPosition = "EndPosition", "(", 4*Integer, ")" ;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
using Orts.Parsers.Msts; // For class S (seconds)
using ORTS.Common;
namespace Orts.Formats.Msts
{
public enum SeasonType { Spring = 0, Summer, Autumn, Winter }
public enum WeatherType { Clear = 0, Snow, Rain }
public enum Difficulty { Easy = 0, Medium, Hard }
public enum EventType {
AllStops = 0, AssembleTrain, AssembleTrainAtLocation, DropOffWagonsAtLocation, PickUpPassengers,
PickUpWagons, ReachSpeed
}
public enum ActivityMode
{
IntroductoryTrainRide = 0,
Player = 2,
Tutorial = 3,
}
public struct LoadData
{
public string Name;
public string Folder;
public LoadPosition LoadPosition;
}
/// <summary>
/// Parse and *.act file.
/// Naming for classes matches the terms in the *.act file.
/// </summary>
public class ActivityFile {
public Tr_Activity Tr_Activity;
public ActivityFile(string filenamewithpath) {
Read(filenamewithpath, false);
}
public ActivityFile(string filenamewithpath, bool headerOnly) {
Read(filenamewithpath, headerOnly);
}
public void Read(string filenamewithpath, bool headerOnly) {
using (STFReader stf = new STFReader(filenamewithpath, false)) {
stf.ParseFile(() => headerOnly && (Tr_Activity != null) && (Tr_Activity.Tr_Activity_Header != null), new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("tr_activity", ()=>{ Tr_Activity = new Tr_Activity(stf, headerOnly); }),
});
if (Tr_Activity == null)
STFException.TraceWarning(stf, "Missing Tr_Activity statement");
}
}
public void InsertORSpecificData(string filenamewithpath)
{
using (STFReader stf = new STFReader(filenamewithpath, false))
{
var tr_activityTokenPresent = false;
stf.ParseFile(() => false && (Tr_Activity.Tr_Activity_Header != null), new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("tr_activity", ()=>{ tr_activityTokenPresent = true; Tr_Activity.InsertORSpecificData (stf); }),
});
if (!tr_activityTokenPresent)
STFException.TraceWarning(stf, "Missing Tr_Activity statement");
}
}
// Used for explore in activity mode
public ActivityFile()
{
Tr_Activity = new Tr_Activity();
}
}
public class Tr_Activity {
public int Serial = 1;
public Tr_Activity_Header Tr_Activity_Header;
public Tr_Activity_File Tr_Activity_File;
public Tr_Activity(STFReader stf, bool headerOnly) {
stf.MustMatch("(");
stf.ParseBlock(() => headerOnly && (Tr_Activity_Header != null), new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("tr_activity_file", ()=>{ Tr_Activity_File = new Tr_Activity_File(stf); }),
new STFReader.TokenProcessor("serial", ()=>{ Serial = stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("tr_activity_header", ()=>{ Tr_Activity_Header = new Tr_Activity_Header(stf); }),
});
if (!headerOnly && (Tr_Activity_File == null))
STFException.TraceWarning(stf, "Missing Tr_Activity_File statement");
}
public void InsertORSpecificData(STFReader stf)
{
stf.MustMatch("(");
var tr_activity_fileTokenPresent = false;
stf.ParseBlock(() => false && (Tr_Activity_Header != null), new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("tr_activity_file", ()=>{ tr_activity_fileTokenPresent = true; Tr_Activity_File.InsertORSpecificData (stf); }),
});
if (!tr_activity_fileTokenPresent)
STFException.TraceWarning(stf, "Missing Tr_Activity_File statement");
}
// Used for explore in activity mode
public Tr_Activity()
{
Serial = -1;
Tr_Activity_Header = new Tr_Activity_Header();
Tr_Activity_File = new Tr_Activity_File();
}
}
public class Tr_Activity_Header {
public string RouteID;
public string Name; // AE Display Name
public string Description = " ";
public string Briefing = " ";
public int CompleteActivity = 1; // <CJComment> Should be boolean </CJComment>
public int Type;
public ActivityMode Mode = ActivityMode.Player;
public StartTime StartTime = new StartTime(10, 0, 0);
public SeasonType Season = SeasonType.Summer;
public WeatherType Weather = WeatherType.Clear;
public string PathID;
public int StartingSpeed; // <CJComment> Should be float </CJComment>
public Duration Duration = new Duration(1, 0);
public Difficulty Difficulty = Difficulty.Easy;
public int Animals = 100; // percent
public int Workers; // percent
public int FuelWater = 100; // percent
public int FuelCoal = 100; // percent
public int FuelDiesel = 100; // percent
public string LoadStationsPopulationFile;
public Tr_Activity_Header(STFReader stf) {
stf.MustMatch("(");
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("routeid", ()=>{ RouteID = stf.ReadStringBlock(null); }),
new STFReader.TokenProcessor("name", ()=>{ Name = stf.ReadStringBlock(null); }),
new STFReader.TokenProcessor("description", ()=>{ Description = stf.ReadStringBlock(Description); }),
new STFReader.TokenProcessor("briefing", ()=>{ Briefing = stf.ReadStringBlock(Briefing); }),
new STFReader.TokenProcessor("completeactivity", ()=>{ CompleteActivity = stf.ReadIntBlock(CompleteActivity); }),
new STFReader.TokenProcessor("type", ()=>{ Type = stf.ReadIntBlock(Type); }),
new STFReader.TokenProcessor("mode", ()=>{ Mode = (ActivityMode)stf.ReadIntBlock((int)Mode); }),
new STFReader.TokenProcessor("starttime", ()=>{ StartTime = new StartTime(stf); }),
new STFReader.TokenProcessor("season", ()=>{ Season = (SeasonType)stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("weather", ()=>{ Weather = (WeatherType)stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("pathid", ()=>{ PathID = stf.ReadStringBlock(null); }),
new STFReader.TokenProcessor("startingspeed", ()=>{ StartingSpeed = (int)stf.ReadFloatBlock(STFReader.UNITS.Speed, (float)StartingSpeed); }),
new STFReader.TokenProcessor("duration", ()=>{ Duration = new Duration(stf); }),
new STFReader.TokenProcessor("difficulty", ()=>{ Difficulty = (Difficulty)stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("animals", ()=>{ Animals = stf.ReadIntBlock(Animals); }),
new STFReader.TokenProcessor("workers", ()=>{ Workers = stf.ReadIntBlock(Workers); }),
new STFReader.TokenProcessor("fuelwater", ()=>{ FuelWater = stf.ReadIntBlock(FuelWater); }),
new STFReader.TokenProcessor("fuelcoal", ()=>{ FuelCoal = stf.ReadIntBlock(FuelCoal); }),
new STFReader.TokenProcessor("fueldiesel", ()=>{ FuelDiesel = stf.ReadIntBlock(FuelDiesel); }),
new STFReader.TokenProcessor("ortsloadstationspopulation", ()=>{ LoadStationsPopulationFile = stf.ReadStringBlock(null); }),
});
}
// Used for explore in activity mode
public Tr_Activity_Header()
{
}
}
public class StartTime {
public int Hour;
public int Minute;
public int Second;
public StartTime(int h, int m, int s) {
Hour = h;
Minute = m;
Second = s;
}
public StartTime(STFReader stf) {
stf.MustMatch("(");
Hour = stf.ReadInt(null);
Minute = stf.ReadInt(null);
Second = stf.ReadInt(null);
stf.MustMatch(")");
}
public String FormattedStartTime() {
return Hour.ToString("00") + ":" + Minute.ToString("00") + ":" + Second.ToString("00");
}
}
public class Duration {
int Hour;
int Minute;
int Second;
public Duration(int h, int m) {
Hour = h;
Minute = m;
Second = 0;
}
public Duration(STFReader stf) {
stf.MustMatch("(");
Hour = stf.ReadInt(null);
Minute = stf.ReadInt(null);
stf.MustMatch(")");
}
public int ActivityDuration()
{
return Hour* 3600 + Minute* 60 + Second; // Convert time to seconds
}
public String FormattedDurationTime()
{
return Hour.ToString("00") + ":" + Minute.ToString("00");
}
public String FormattedDurationTimeHMS()
{
return Hour.ToString("00") + ":" + Minute.ToString("00") + ":" + Second.ToString("00");
}
}
public class Tr_Activity_File {
public Player_Service_Definition Player_Service_Definition;
public int NextServiceUID = 1;
public int NextActivityObjectUID = 32786;
public ActivityObjects ActivityObjects;
public ActivityFailedSignals ActivityFailedSignals;
public Events Events;
public Traffic_Definition Traffic_Definition;
public PlatformNumPassengersWaiting PlatformNumPassengersWaiting;
public ActivityRestrictedSpeedZones ActivityRestrictedSpeedZones;
public bool AIBlowsHornAtLevelCrossings { get; private set; } = false;
public LevelCrossingHornPattern AILevelCrossingHornPattern { get; private set; } = LevelCrossingHornPattern.Single;
public Tr_Activity_File(STFReader stf) {
stf.MustMatch("(");
var parser = new List<STFReader.TokenProcessor> {
new STFReader.TokenProcessor("player_service_definition",()=>{ Player_Service_Definition = new Player_Service_Definition(stf); }),
new STFReader.TokenProcessor("nextserviceuid",()=>{ NextServiceUID = stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("nextactivityobjectuid",()=>{ NextActivityObjectUID = stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("events",()=>{ Events = new Events(stf); }),
new STFReader.TokenProcessor("traffic_definition",()=>{ Traffic_Definition = new Traffic_Definition(stf); }),
new STFReader.TokenProcessor("activityobjects",()=>{ ActivityObjects = new ActivityObjects(stf); }),
new STFReader.TokenProcessor("platformnumpassengerswaiting",()=>{ PlatformNumPassengersWaiting = new PlatformNumPassengersWaiting(stf); }), // 35 files. To test, use EUROPE1\ACTIVITIES\aftstorm.act
new STFReader.TokenProcessor("activityfailedsignals",()=>{ ActivityFailedSignals = new ActivityFailedSignals(stf); }),
new STFReader.TokenProcessor("activityrestrictedspeedzones",()=>{ ActivityRestrictedSpeedZones = new ActivityRestrictedSpeedZones(stf); }), // 27 files. To test, use EUROPE1\ACTIVITIES\lclsrvce.act
};
parser.AddRange(ORSpecificDataTokenProcessors(stf));
stf.ParseBlock(parser);
}
// Used for explore in activity mode
public Tr_Activity_File()
{
Player_Service_Definition = new Player_Service_Definition();
}
//public void ClearStaticConsists()
//{
// NextActivityObjectUID = 32786;
// ActivityObjects.Clear();
//}
public void InsertORSpecificData(STFReader stf)
{
stf.MustMatch("(");
var parser = new List<STFReader.TokenProcessor> {
new STFReader.TokenProcessor("events",()=>
{
if ( Events == null) Events = new Events(stf);
else Events.InsertORSpecificData (stf);
}
),
};
parser.AddRange(ORSpecificDataTokenProcessors(stf));
stf.ParseBlock(parser);
}
private IEnumerable<STFReader.TokenProcessor> ORSpecificDataTokenProcessors(STFReader stf)
{
yield return new STFReader.TokenProcessor("ortsaihornatcrossings", () =>
{
AIBlowsHornAtLevelCrossings = stf.ReadIntBlock(Convert.ToInt32(AIBlowsHornAtLevelCrossings)) > 0;
});
yield return new STFReader.TokenProcessor("ortsaicrossinghornpattern", () =>
{
if (Enum.TryParse<LevelCrossingHornPattern>(stf.ReadStringBlock(""), ignoreCase: true, out var value))
AILevelCrossingHornPattern = value;
});
}
}
public class Player_Service_Definition {
public string Name;
public Player_Traffic_Definition Player_Traffic_Definition;
public Player_Service_Definition(STFReader stf) {
stf.MustMatch("(");
Name = stf.ReadString();
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("player_traffic_definition", ()=>{ Player_Traffic_Definition = new Player_Traffic_Definition(stf); }),
});
}
// Used for explore in activity mode
public Player_Service_Definition()
{
Player_Traffic_Definition = new Player_Traffic_Definition();
}
}
public class Player_Traffic_Definition {
public int Time;
public List<Player_Traffic_Item> Player_Traffic_List = new List<Player_Traffic_Item>();
public Player_Traffic_Definition(STFReader stf) {
DateTime baseDT = new DateTime();
DateTime arrivalTime = new DateTime();
DateTime departTime = new DateTime();
int skipCount = 0;
float distanceDownPath = new float();
int platformStartID = 0;
stf.MustMatch("(");
Time = (int)stf.ReadFloat(STFReader.UNITS.Time, null);
// Clumsy parsing. You only get a new Player_Traffic_Item in the list after a PlatformStartId is met.
// Blame lies with Microsoft for poor design of syntax.
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("arrivaltime", ()=>{ arrivalTime = baseDT.AddSeconds(stf.ReadFloatBlock(STFReader.UNITS.Time, null)); }),
new STFReader.TokenProcessor("departtime", ()=>{ departTime = baseDT.AddSeconds(stf.ReadFloatBlock(STFReader.UNITS.Time, null)); }),
new STFReader.TokenProcessor("skipcount", ()=>{ skipCount = stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("distancedownpath", ()=>{ distanceDownPath = stf.ReadFloatBlock(STFReader.UNITS.Distance, null); }),
new STFReader.TokenProcessor("platformstartid", ()=>{ platformStartID = stf.ReadIntBlock(null);
Player_Traffic_List.Add(new Player_Traffic_Item(arrivalTime, departTime, skipCount, distanceDownPath, platformStartID)); }),
});
}
// Used for explore in activity mode
public Player_Traffic_Definition()
{
}
}
public class Player_Traffic_Item {
public DateTime ArrivalTime;
public DateTime DepartTime;
public float DistanceDownPath;
public int PlatformStartID;
public Player_Traffic_Item(DateTime arrivalTime, DateTime departTime, int skipCount, float distanceDownPath, int platformStartID) {
ArrivalTime = arrivalTime;
DepartTime = departTime;
DistanceDownPath = distanceDownPath;
PlatformStartID = platformStartID;
}
}
public class Service_Definition {
public string Name;
public int Time;
public int UiD;
public List<Service_Item> ServiceList = new List<Service_Item>();
float efficiency;
int skipCount;
float distanceDownPath = new float();
int platformStartID;
public Service_Definition(STFReader stf) {
stf.MustMatch("(");
Name = stf.ReadString();
Time = (int)stf.ReadFloat(STFReader.UNITS.Time, null);
stf.MustMatch("uid");
UiD = stf.ReadIntBlock(null);
// Clumsy parsing. You only get a new Service_Item in the list after a PlatformStartId is met.
// Blame lies with Microsoft for poor design of syntax.
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("efficiency", ()=>{ efficiency = stf.ReadFloatBlock(STFReader.UNITS.Any, null); }),
new STFReader.TokenProcessor("skipcount", ()=>{ skipCount = stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("distancedownpath", ()=>{ distanceDownPath = stf.ReadFloatBlock(STFReader.UNITS.Distance, null); }),
new STFReader.TokenProcessor("platformstartid", ()=>{ platformStartID = stf.ReadIntBlock(null);
ServiceList.Add(new Service_Item(efficiency, skipCount, distanceDownPath, platformStartID)); }),
});
}
// This is used to convert the player traffic definition into an AI train service definition for autopilot mode
public Service_Definition(string service_Definition, Player_Traffic_Definition player_Traffic_Definition)
{
Name = service_Definition;
Time = player_Traffic_Definition.Time;
UiD = 0;
foreach (Player_Traffic_Item player_Traffic_Item in player_Traffic_Definition.Player_Traffic_List)
{
efficiency = 0.95f; // Not present in player traffic definition
distanceDownPath = player_Traffic_Item.DistanceDownPath;
platformStartID = player_Traffic_Item.PlatformStartID;
skipCount = 0;
ServiceList.Add(new Service_Item(efficiency, skipCount, distanceDownPath, platformStartID));
}
}
//================================================================================================//
/// <summary>
/// For restore
/// <\summary>
///
public Service_Definition ()
{ }
//================================================================================================//
/// <summary>
/// Save of useful Service Items parameters
/// <\summary>
///
public void Save(BinaryWriter outf)
{
if (ServiceList == null || ServiceList.Count == 0)
{
outf.Write(-1);
}
else
{
outf.Write (ServiceList.Count);
foreach (Service_Item thisServiceItem in ServiceList)
{
outf.Write(thisServiceItem.Efficiency);
outf.Write(thisServiceItem.PlatformStartID);
}
}
}
}
public class Service_Item
{
public float Efficiency = new float();
public int SkipCount;
public float DistanceDownPath = new float();
public int PlatformStartID;
public Service_Item(float efficiency, int skipCount, float distanceDownPath, int platformStartID) {
Efficiency = efficiency;
SkipCount = skipCount;
DistanceDownPath = distanceDownPath;
PlatformStartID = platformStartID;
}
}
/// <summary>
/// Parses Service_Definition objects and saves them in ServiceDefinitionList.
/// </summary>
public class Traffic_Definition {
public string Name;
public TrafficFile TrafficFile;
public List<Service_Definition> ServiceDefinitionList = new List<Service_Definition>();
public Traffic_Definition(STFReader stf) {
stf.MustMatch("(");
Name = stf.ReadString();
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("service_definition", ()=>{ ServiceDefinitionList.Add(new Service_Definition(stf)); }),
});
TrafficFile = new TrafficFile(Path.Combine(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(stf.FileName)), "Traffic"), Name + ".trf"));
}
}
/// <summary>
/// Parses Event objects and saves them in EventList.
/// </summary>
public class Events {
public List<Event> EventList = new List<Event>();
public Events(STFReader stf) {
stf.MustMatch("(");
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("eventcategorylocation", ()=>{ EventList.Add(new EventCategoryLocation(stf)); }),
new STFReader.TokenProcessor("eventcategoryaction", ()=>{ EventList.Add(new EventCategoryAction(stf)); }),
new STFReader.TokenProcessor("eventcategorytime", ()=>{ EventList.Add(new EventCategoryTime(stf)); }),
});
}
public void InsertORSpecificData (STFReader stf)
{
stf.MustMatch("(");
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("eventcategorylocation", ()=>{ TryModify(0, stf); }),
new STFReader.TokenProcessor("eventcategoryaction", ()=>{ TryModify(1, stf); }),
new STFReader.TokenProcessor("eventcategorytime", ()=>{ TryModify(2, stf); }),
});
}
public void TryModify(int Category, STFReader stf)
{
Event origEvent;
bool wrongEventID = false;
int modifiedID = -1;
try
{
stf.MustMatch("(");
stf.MustMatch("id");
stf.MustMatch("(");
modifiedID = stf.ReadInt(null);
stf.MustMatch(")");
origEvent = EventList.Find(x => x.ID == modifiedID);
if (origEvent == null)
{
wrongEventID = true;
Trace.TraceWarning("Skipped event {0} not present in base activity file", modifiedID);
stf.SkipRestOfBlock();
}
else
{
wrongEventID = !TestMatch(Category, origEvent);
if (!wrongEventID)
{
origEvent.AddOrModifyEvent(stf, Path.GetDirectoryName(stf.FileName));
}
else
{
Trace.TraceWarning("Skipped event {0} of event category not matching with base activity file", modifiedID);
stf.SkipRestOfBlock();
}
}
}
catch (Exception error)
{
Trace.WriteLine(new FileLoadException("Error in additional activity file", error));
}
}
private bool TestMatch(int category, Event origEvent)
{
if (category == 0 && origEvent is EventCategoryLocation) return true;
if (category == 1 && origEvent is EventCategoryAction) return true;
if (category == 2 && origEvent is EventCategoryTime) return true;
return false;
}
}
public enum ORTSActSoundFileTypes
{
None,
Everywhere,
Cab,
Pass,
Ground,
Location
}
/// <summary>
/// The 3 types of event are inherited from the abstract Event class.
/// </summary>
public abstract class Event {
public int ID;
public string Name;
public int Activation_Level;
public Outcomes Outcomes;
public string TextToDisplayOnCompletionIfTriggered = "";
public string TextToDisplayOnCompletionIfNotTriggered = "";
public Boolean Reversible;
public int ORTSContinue = -1;
public string ORTSActSoundFile;
public ORTSActSoundFileTypes ORTSActSoundFileType;
public ORTSWeatherChange ORTSWeatherChange;
public string TrainService = "";
public int TrainStartingTime = -1;
public virtual void AddOrModifyEvent (STFReader stf, string fileName)
{ }
}
public class EventCategoryLocation : Event {
public bool TriggerOnStop; // Value assumed if property not found.
public int TileX;
public int TileZ;
public float X;
public float Z;
public float RadiusM;
public EventCategoryLocation(STFReader stf) {
stf.MustMatch("(");
AddOrModifyEvent(stf, stf.FileName);
}
public override void AddOrModifyEvent (STFReader stf, string fileName)
{
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("eventtypelocation", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); }),
new STFReader.TokenProcessor("id", ()=>{ ID = stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("ortstriggeringtrain", ()=>{ ParseTrain(stf); }),
new STFReader.TokenProcessor("activation_level", ()=>{ Activation_Level = stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("outcomes", ()=>
{
if (Outcomes == null)
Outcomes = new Outcomes(stf, fileName);
else
Outcomes.CreateOrModifyOutcomes(stf, fileName); }),
new STFReader.TokenProcessor("name", ()=>{ Name = stf.ReadStringBlock(null); }),
new STFReader.TokenProcessor("texttodisplayoncompletioniftriggered", ()=>{ TextToDisplayOnCompletionIfTriggered = stf.ReadStringBlock(null); }),
new STFReader.TokenProcessor("texttodisplayoncompletionifnottriggered", ()=>{ TextToDisplayOnCompletionIfNotTriggered = stf.ReadStringBlock(null); }),
new STFReader.TokenProcessor("triggeronstop", ()=>{ TriggerOnStop = stf.ReadBoolBlock(true); }),
new STFReader.TokenProcessor("location", ()=>{
stf.MustMatch("(");
TileX = stf.ReadInt(null);
TileZ = stf.ReadInt(null);
X = stf.ReadFloat(STFReader.UNITS.None, null);
Z = stf.ReadFloat(STFReader.UNITS.None, null);
RadiusM = stf.ReadFloat(STFReader.UNITS.Distance, null);
stf.MustMatch(")");
}),
new STFReader.TokenProcessor("ortscontinue", ()=>{ ORTSContinue = stf.ReadIntBlock(0); }),
new STFReader.TokenProcessor("ortsactsoundfile", ()=>
{
stf.MustMatch("(");
var tempString = stf.ReadString();
ORTSActSoundFile =Path.Combine(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(fileName)), "SOUND"), tempString);
try
{
ORTSActSoundFileType = (ORTSActSoundFileTypes)Enum.Parse(typeof(ORTSActSoundFileTypes), stf.ReadString());
}
catch(ArgumentException)
{
stf.StepBackOneItem();
STFException.TraceInformation(stf, "Skipped unknown activity sound file type " + stf.ReadString());
ORTSActSoundFileType = ORTSActSoundFileTypes.None;
}
stf.MustMatch(")");
}),
new STFReader.TokenProcessor("ortsweatherchange", ()=>{ ORTSWeatherChange = new ORTSWeatherChange(stf);}),
});
}
protected void ParseTrain(STFReader stf)
{
stf.MustMatch("(");
TrainService = stf.ReadString();
TrainStartingTime = stf.ReadInt(-1);
stf.SkipRestOfBlock();
}
}
/// <summary>
/// Parses all types of action events.
/// Save type of action event in Type. MSTS syntax isn't fully hierarchical, so using inheritance here instead of Type would be awkward.
/// </summary>
public class EventCategoryAction : Event {
public EventType Type;
public WagonList WagonList;
public Nullable<uint> SidingId; // May be specified inside the Wagon_List instead. Nullable as can't use -1 to indicate not set.
public float SpeedMpS;
//private const float MilespHourToMeterpSecond = 0.44704f;
public EventCategoryAction(STFReader stf) {
stf.MustMatch("(");
AddOrModifyEvent(stf, stf.FileName);
}
public override void AddOrModifyEvent(STFReader stf, string fileName)
{
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("eventtypeallstops", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); Type = EventType.AllStops; }),
new STFReader.TokenProcessor("eventtypeassembletrain", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); Type = EventType.AssembleTrain; }),
new STFReader.TokenProcessor("eventtypeassembletrainatlocation", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); Type = EventType.AssembleTrainAtLocation; }),
new STFReader.TokenProcessor("eventtypedropoffwagonsatlocation", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); Type = EventType.DropOffWagonsAtLocation; }),
new STFReader.TokenProcessor("eventtypepickuppassengers", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); Type = EventType.PickUpPassengers; }),
new STFReader.TokenProcessor("eventtypepickupwagons", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); Type = EventType.PickUpWagons; }),
new STFReader.TokenProcessor("eventtypereachspeed", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); Type = EventType.ReachSpeed; }),
new STFReader.TokenProcessor("id", ()=>{ ID = stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("activation_level", ()=>{ Activation_Level = stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("outcomes", ()=>
{
if (Outcomes == null)
Outcomes = new Outcomes(stf, fileName);
else
Outcomes.CreateOrModifyOutcomes(stf, fileName); }),
new STFReader.TokenProcessor("texttodisplayoncompletioniftriggered", ()=>{ TextToDisplayOnCompletionIfTriggered = stf.ReadStringBlock(""); }),
new STFReader.TokenProcessor("texttodisplayoncompletionifnottriggered", ()=>{ TextToDisplayOnCompletionIfNotTriggered = stf.ReadStringBlock(""); }),
new STFReader.TokenProcessor("name", ()=>{ Name = stf.ReadStringBlock(""); }),
new STFReader.TokenProcessor("wagon_list", ()=>{ WagonList = new WagonList(stf, Type); }),
new STFReader.TokenProcessor("sidingitem", ()=>{ SidingId = (uint)stf.ReadIntBlock(null); }),
new STFReader.TokenProcessor("speed", ()=>{ SpeedMpS = stf.ReadFloatBlock(STFReader.UNITS.Speed, null); }),
new STFReader.TokenProcessor("reversable_event", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); Reversible = true; }),
// Also support the correct spelling !
new STFReader.TokenProcessor("reversible_event", ()=>{ stf.MustMatch("("); stf.MustMatch(")"); Reversible = true; }),
new STFReader.TokenProcessor("ortscontinue", ()=>{ ORTSContinue = stf.ReadIntBlock(0); }),
new STFReader.TokenProcessor("ortsactsoundfile", ()=>
{
stf.MustMatch("(");
var tempString = stf.ReadString();
ORTSActSoundFile =Path.Combine(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(fileName)), "SOUND"), tempString);
try
{
ORTSActSoundFileType = (ORTSActSoundFileTypes)Enum.Parse(typeof(ORTSActSoundFileTypes), stf.ReadString());
}
catch(ArgumentException)
{
stf.StepBackOneItem();
STFException.TraceInformation(stf, "Skipped unknown activity sound file type " + stf.ReadString());
ORTSActSoundFileType = ORTSActSoundFileTypes.None;
}
stf.MustMatch(")");
}),
});
}
}
public class WagonList {
public List<WorkOrderWagon> WorkOrderWagonList = new List<WorkOrderWagon>();
Nullable<uint> uID; // Nullable as can't use -1 to indicate not set.
Nullable<uint> sidingId; // May be specified outside the Wagon_List instead.
string description = ""; // Value assumed if property not found.
public WagonList(STFReader stf, EventType eventType) {
stf.MustMatch("(");
// "Drop Off" Wagon_List sometimes lacks a Description attribute, so we create the wagon _before_ description
// is parsed. Bad practice, but not very dangerous as each Description usually repeats the same data.
stf.ParseBlock(new STFReader.TokenProcessor[] {
new STFReader.TokenProcessor("uid", ()=>{ uID = stf.ReadUIntBlock(null); }),
new STFReader.TokenProcessor("sidingitem", ()=>{ sidingId = stf.ReadUIntBlock(null);
WorkOrderWagonList.Add(new WorkOrderWagon(uID.Value, sidingId.Value, description));}),
new STFReader.TokenProcessor("description", ()=>{ description = stf.ReadStringBlock(""); }),
});
}
}