protected void enableTrainSound(Train train)
 {
     AudioSource audioSource = train.GetComponent<AudioSource>();
     if (audioSource) {
         audioSource.enabled = true;
     }
 }
Example #2
0
 /// <summary>
 /// Инициализирует билет по поезду, в котором едет пассажир, типу вагона и
 /// пассажиру, который едет по этому билету. Устанавливает ссылки от себя 
 /// на поезд и на пассажира, а также  ссылки от поезда и от пассажира на себя.
 /// </summary>
 /// <param name="Train">Поезд, в котором едет пассажир.</param>
 /// <param name="Type">Тип вагона.</param>
 public Ticket(Train Train, string Type, Passenger Passenger)
 {
     _train      = Train;
     _type       = Type;
     _passenger  = Passenger;
     Associate(Train, Passenger);
 }
    protected override void retrieve()
    {
        string trainName = selectedTrainStorage.Get();
        selectedTrainStorage.Delete();

        train = retrieve(trainName);
    }
    public Trainmovsegment()
    {
        this.lvtrain_id = new Train();

        Clear();
        StopLocation.LoadList();
    }
Example #5
0
		/// <summary>Moves the air brake handle</summary>
		/// <param name="Train">The train</param>
		/// <param name="RelativeDirection">The direction: -1 for decrease, 1 for increase</param>
		internal static void ApplyAirBrakeHandle(Train Train, int RelativeDirection)
		{
			if (Train.Cars[Train.DriverCar].Specs.BrakeType == CarBrakeType.AutomaticAirBrake)
			{
				if (RelativeDirection == -1)
				{
					if (Train.Specs.AirBrake.Handle.Driver == AirBrakeHandleState.Service)
					{
						ApplyAirBrakeHandle(Train, AirBrakeHandleState.Lap);
					}
					else
					{
						ApplyAirBrakeHandle(Train, AirBrakeHandleState.Release);
					}
				}
				else if (RelativeDirection == 1)
				{
					if (Train.Specs.AirBrake.Handle.Driver == AirBrakeHandleState.Release)
					{
						ApplyAirBrakeHandle(Train, AirBrakeHandleState.Lap);
					}
					else
					{
						ApplyAirBrakeHandle(Train, AirBrakeHandleState.Service);
					}
				}
				Game.AddBlackBoxEntry(Game.BlackBoxEventToken.None);
			}
		}
 public void Decrease(Train train, int passengersToDecrease)
 {
     if (!isSet(train)) {
         passengersPerTrain[train] = initialPassengers;
     }
     passengersPerTrain[train] -= passengersToDecrease;
 }
Example #7
0
 public void AddExistingTrainTest()
 {
     Administration admin = new Administration();
     Train train = new Train(1, 1);
     admin.Add(train);
     Assert.AreEqual(false, admin.Add(train));
 }
Example #8
0
		/// <summary>Applies a reverser notch</summary>
		/// <param name="Train">The train</param>
		/// <param name="Value">The notch to apply</param>
		/// <param name="Relative">Whether this is an absolute value or relative to the previous</param>
		internal static void ApplyReverser(Train Train, int Value, bool Relative)
		{
			int a = Train.Specs.CurrentReverser.Driver;
			int r = Relative ? a + Value : Value;
			if (r < -1) r = -1;
			if (r > 1) r = 1;
			if (a != r)
			{
				Train.Specs.CurrentReverser.Driver = r;
				if (Train.Plugin != null)
				{
					Train.Plugin.UpdateReverser();
				}
				Game.AddBlackBoxEntry(Game.BlackBoxEventToken.None);
				// sound
				if (a == 0 & r != 0)
				{
					Sounds.SoundBuffer buffer = Train.Cars[Train.DriverCar].Sounds.ReverserOn.Buffer;
					if (buffer == null) return;
					OpenBveApi.Math.Vector3 pos = Train.Cars[Train.DriverCar].Sounds.ReverserOn.Position;
					Sounds.PlaySound(buffer, 1.0, 1.0, pos, Train, Train.DriverCar, false);
				}
				else if (a != 0 & r == 0)
				{
					Sounds.SoundBuffer buffer = Train.Cars[Train.DriverCar].Sounds.ReverserOff.Buffer;
					if (buffer == null) return;
					OpenBveApi.Math.Vector3 pos = Train.Cars[Train.DriverCar].Sounds.ReverserOff.Position;
					Sounds.PlaySound(buffer, 1.0, 1.0, pos, Train, Train.DriverCar, false);
				}
			}
		}
Example #9
0
			/// <summary>Adds a delayed handle state change</summary>
			/// <param name="Train">The train to add the delayed state change to</param>
			/// <param name="Value">The value to add or subtract</param>
			/// <param name="Delay">The delay in seconds</param>
			internal void AddChange(Train Train, int Value, double Delay)
			{
				int n = DelayedChanges.Length;
				Array.Resize<HandleChange>(ref DelayedChanges, n + 1);
				DelayedChanges[n].Value = Value;
				DelayedChanges[n].Time = Game.SecondsSinceMidnight + Delay;
			}
Example #10
0
        [TestMethod] public void AddsFirstTimetableCall() {
            var station = TestDataFactory.CreateStation1();
            var target = new Train(TrainCategory.Freight, "G1234");
            var call = new StationCall(station.Tracks.First(), new Time(12,30) , new Time(12,45));
            target.Add(call);

        }
 [TestInitialize] public void TestInitialize() {
     TestDataFactory.Init();
     layout = TestDataFactory.Layout();
     stretch = layout.TrackStretches.First();
     train = TestDataFactory.CreateTrain1();
     target = new TrackStretchCoordinator(stretch);
 }
Example #12
0
 public void WhenSecondTimetableCallIsAfterLastThenThrows() {
     var station = TestDataFactory.CreateStation1();
     var target = new Train(TrainCategory.Freight, "G1234");
     var call1 = new StationCall(station.Tracks.First(), new Time(12, 30), new Time(12, 45));
     var call2 = new StationCall(station.Tracks.First(), new Time(12, 50), new Time(12, 55));
     target.Add(call1);
     target.Add(call2);
 }
    private void addPlayer(Train train, NetworkPlayer owner, NetworkTrainPlayers players)
    {
        string newTrainName = RemoteTrainName.GetNameFor(train, owner);
        Train newTrain = clone(train, newTrainName);

        NetworkTrainPlayer player = NetworkTrainPlayerFactory.Create(newTrain, owner);
        players.AddPlayer(player);
    }
Example #14
0
 public void AddedTrainCanBeFoundTest()
 {
     Administration admin = new Administration();
     Train train = new Train(1, 1);
     admin.Add(train);
     Train foundTrain = admin.FindTrain(1);
     Assert.AreEqual(foundTrain, train);
 }
Example #15
0
 public void WriteTrain(string filename, Train train, BaseFormater formater)
 {
     Stream fs = new FileStream(filename, FileMode.Create);
     foreach (IFilter filter in filters)
         fs = filter.Apply(fs, FilterMode.Write);
     formater.WriteTrain(train, fs);
     fs.Close();
 }
Example #16
0
 public void NextStationTest()
 {
     Station station = new Station("test");
     Train nextTrain = new Train(1, 2);
     station.NextTrain = nextTrain;
     Assert.AreEqual(nextTrain, station.NextTrain);
     Assert.AreEqual(1, nextTrain.TrainUnit);
 }
Example #17
0
 public void LastStationTest()
 {
     Station station = new Station("test");
     Train lastTrain = new Train(1, 2);
     station.LastTrain = lastTrain;
     Assert.AreEqual(lastTrain, station.LastTrain);
     Assert.AreEqual(1, lastTrain.TrainUnit);
 }
Example #18
0
 public void CalculateStandingSpotsTest()
 {
     Train train = new Train(1, 1);
     Wagon wagon1 = new Wagon(1, 25, 10);
     Wagon wagon2 = new Wagon(2, 15, 4);
     train.Add(wagon1);
     train.Add(wagon2);
     Assert.AreEqual(14, train.TotalStandingSpots);
 }
Example #19
0
 public override Train ReadTrain(Stream stream)
 {
     sr = new StreamReader(stream);
     Train train = new Train(Int32.Parse(sr.ReadLine()));
     int count = Int32.Parse(sr.ReadLine());
     for (int i = 0; i < count; i++)
         train.AddCoach(ReadCoach());
     return train;
 }
Example #20
0
		/// <summary>Un-derails a train</summary>
		/// <param name="Train">The train</param>
		internal static void UnderailTrain(Train Train)
		{
			Train.Derailed = false;
			for (int i = 0; i < Train.Cars.Length; i++)
			{
				Train.Cars[i].Specs.CurrentRollDueToTopplingAngle = 0.0;
				Train.Cars[i].Derailed = false;
			}
		}
Example #21
0
 public override void WriteTrain(Train train, Stream stream)
 {
     sw = new BinaryWriter(stream);
     sw.Write(train.Number);
     sw.Write(train.Coaches.Count);
     foreach (Coach coach in train)
         WriteCoach(coach);
     sw.Close();
 }
Example #22
0
 public override Train ReadTrain(Stream stream)
 {
     sr = new BinaryReader(stream);
     Train train = new Train(sr.ReadInt32());
     int count = sr.ReadInt32();
     for (int i = 0; i < count; i++)
         train.AddCoach(ReadCoach());
     return train;
 }
Example #23
0
 public static void AddTrain(Train train)
 {
     using (var db = new TrainContext())
     {
         var tr = db.Set<Train>();
         tr.Add(train);
         db.SaveChanges();
     }
 }
Example #24
0
 public static void DeleteTrain(Train train)
 {
     using (var db = new TrainContext())
     {
         db.Trains.Attach(train);
         db.Trains.Remove(train);
         db.SaveChanges();
     }
 }
 public static Train CreateTrain1() {
     var stations = Stations.ToArray();
     var train = new Train(TrainCategory.Freight, "G1234");
     var startTime = new Time(12, 00);
     train.Add(new StationCall(stations[0]["3"], startTime, startTime.Add(30)));
     train.Add(new StationCall(stations[1]["2"], startTime.Add(50), startTime.Add(57)));
     train.Add(new StationCall(stations[2]["1"], startTime.Add(70), startTime.Add(180)));
     return train;
 }
 protected virtual void gameObjectOperations(Train train)
 {
     GameObjectOperations.To(main)
         .Hide()
         .SetRotation(train.gameObject);
     GameObjectOperations.To(train.gameObject)
         .SetParent(main)
         .SetPosition(main);
 }
 public static Train CreateTrain2() {
     var stations = Stations.ToArray();
     var train = new Train(TrainCategory.Passenger, "P4321");
     var startTime = new Time(12, 00);
     train.Add(new StationCall(stations[2]["2"], startTime, startTime.Add(30)));
     train.Add(new StationCall(stations[1]["1"], startTime.Add(45), startTime.Add(51)));
     train.Add(new StationCall(stations[0]["3"], startTime.Add(70), startTime.Add(180)));
     return train;
 }
    public Trainmovsegment(double train_id, DateTime data_ocup)
    {
        this.lvtrain_id = new Train();
        Clear();

        this.lvtrain_id.Train_id = train_id;
        this.lvdata_ocup = data_ocup;
        Load();
        StopLocation.LoadList();
    }
Example #29
0
        // when the train comes
        public void StepOn(Train train, uint time)
        {
            endOfWaiting = time;

            using (StreamWriter file = new StreamWriter(MainObjects.fileNameForWaitings, true))
            {
                file.WriteLine(endOfWaiting - startOfWaiting);
            }

            Console.WriteLine("{0} is stepping on the train {1} at {2}.", name, train.number, time);
        }
Example #30
0
 // when train is going to the next station people need to catch the train
 // the station manages all this work
 public void TrainGoing(Train train, uint time)
 {
     while (train.currentAmount < Train.MAX_CAPACITY && passengers.Count > 0)
     {
         var passenger = passengers.Dequeue();
         passenger.relatedTrain = train;
         passenger.StepOn(train, time);
         train.passengers.Add(passenger);
         ++train.currentAmount;
     }
 }
Example #31
0
        protected override void Elapse(ref ElapseData data)
        {
            if (externalCrashed)
            {
                //Yuck
                for (int i = 0; i < Train.Cars[Train.DriverCar].Sounds.Plugin.Length; i++)
                {
                    if (Train.Cars[Train.DriverCar].Sounds.Plugin[i].IsPlaying)
                    {
                        Train.Cars[Train.DriverCar].Sounds.Plugin[i].Stop();
                    }
                }
                Train.UnloadPlugin();
                return;
            }
            if (!string.IsNullOrEmpty(lastError))
            {
                //TrainManagercurrentHost.A("ERROR: The proxy plugin " + PluginFile + " generated the following error:");
                //Program.FileSystem.AppendToLogFile(pluginProxy.callback.lastError);
                lastError = string.Empty;
            }

            try
            {
                ElapseProxy e         = new ElapseProxy(data, Panel, Sound);
                ElapseProxy proxyData = pipeProxy.Elapse(e);
                Panel = proxyData.Panel;
                Sound = proxyData.Sound;
                for (int i = 0; i < Sound.Length; i++)
                {
                    if (Sound[i] != LastSound[i])
                    {
                        if (Sound[i] == SoundInstructions.Stop)
                        {
                            if (i < Train.Cars[Train.DriverCar].Sounds.Plugin.Length)
                            {
                                Train.Cars[Train.DriverCar].Sounds.Plugin[i].Stop();
                            }
                        }
                        else if (Sound[i] > SoundInstructions.Stop & Sound[i] <= SoundInstructions.PlayLooping)
                        {
                            if (i < Train.Cars[Train.DriverCar].Sounds.Plugin.Length)
                            {
                                SoundBuffer buffer = Train.Cars[Train.DriverCar].Sounds.Plugin[i].Buffer;
                                if (buffer != null)
                                {
                                    double volume = (double)(Sound[i] - SoundInstructions.Stop) / (SoundInstructions.PlayLooping - SoundInstructions.Stop);
                                    if (Train.Cars[Train.DriverCar].Sounds.Plugin[i].IsPlaying)
                                    {
                                        Train.Cars[Train.DriverCar].Sounds.Plugin[i].Source.Volume = volume;
                                    }
                                    else
                                    {
                                        Train.Cars[Train.DriverCar].Sounds.Plugin[i].Play(1.0, volume, Train.Cars[Train.DriverCar], true);
                                    }
                                }
                            }
                        }
                        else if (Sound[i] == SoundInstructions.PlayOnce)
                        {
                            if (i < Train.Cars[Train.DriverCar].Sounds.Plugin.Length)
                            {
                                SoundBuffer buffer = Train.Cars[Train.DriverCar].Sounds.Plugin[i].Buffer;
                                if (buffer != null)
                                {
                                    Train.Cars[Train.DriverCar].Sounds.Plugin[i].Play(1.0, 1.0, Train.Cars[Train.DriverCar], false);
                                }
                            }

                            Sound[i] = SoundInstructions.Continue;
                        }
                        else if (Sound[i] != SoundInstructions.Continue)
                        {
                            PluginValid = false;
                        }

                        LastSound[i] = Sound[i];
                    }
                    else
                    {
                        if ((Sound[i] < SoundInstructions.Stop | Sound[i] > SoundInstructions.PlayLooping) && Sound[i] != SoundInstructions.PlayOnce & Sound[i] != SoundInstructions.Continue)
                        {
                            PluginValid = false;
                        }
                    }
                }
                data = proxyData.Data;
            }
            catch
            {
                lastError       = externalCrashed.ToString();
                externalCrashed = true;
            }
        }
        //================================================================================================//
        /// <summary>
        /// Reset train references after restore
        /// </summary>
        public void RestoreTrains(List <Train> trains, int sectionIndex)
        {
            // Occupy
            Dictionary <int[], int> tempTrains = new Dictionary <int[], int>();

            foreach (KeyValuePair <Train.TrainRouted, int> thisOccupy in OccupationState)
            {
                int[] trainKey = new int[2];
                trainKey[0] = thisOccupy.Key.Train.Number;
                trainKey[1] = thisOccupy.Key.TrainRouteDirectionIndex;
                int direction = thisOccupy.Value;
                tempTrains.Add(trainKey, direction);
            }

            OccupationState.Clear();

            foreach (KeyValuePair <int[], int> thisTemp in tempTrains)
            {
                int[] trainKey   = thisTemp.Key;
                int   number     = trainKey[0];
                int   routeIndex = trainKey[1];
                int   direction  = thisTemp.Value;
                Train thisTrain  = SignalEnvironment.FindTrain(number, trains);
                if (thisTrain != null)
                {
                    Train.TrainRouted thisTrainRouted = routeIndex == 0 ? thisTrain.RoutedForward : thisTrain.RoutedBackward;
                    OccupationState.Add(thisTrainRouted, direction);
                }
            }

            // Reserved

            if (TrainReserved != null)
            {
                int   number        = TrainReserved.Train.Number;
                Train reservedTrain = SignalEnvironment.FindTrain(number, trains);
                if (reservedTrain != null)
                {
                    int  reservedDirection = TrainReserved.TrainRouteDirectionIndex;
                    bool validreserve      = true;

                    // check if reserved section is on train's route except when train is in explorer or manual mode
                    if (reservedTrain.ValidRoute[reservedDirection].Count > 0 && reservedTrain.ControlMode != TrainControlMode.Explorer && reservedTrain.ControlMode != TrainControlMode.Manual)
                    {
                        _            = reservedTrain.ValidRoute[reservedDirection].GetRouteIndex(sectionIndex, reservedTrain.PresentPosition[Direction.Forward].RouteListIndex);
                        validreserve = reservedTrain.ValidRoute[reservedDirection].GetRouteIndex(sectionIndex, reservedTrain.PresentPosition[Direction.Forward].RouteListIndex) >= 0;
                    }

                    if (validreserve || reservedTrain.ControlMode == TrainControlMode.Explorer)
                    {
                        TrainReserved = reservedDirection == 0 ? reservedTrain.RoutedForward : reservedTrain.RoutedBackward;
                    }
                    else
                    {
                        Trace.TraceInformation("Invalid reservation for train : {0} [{1}], section : {2} not restored", reservedTrain.Name, reservedDirection, sectionIndex);
                    }
                }
                else
                {
                    TrainReserved = null;
                }
            }

            // PreReserved
            Queue <Train.TrainRouted> queue = new Queue <Train.TrainRouted>(TrainPreReserved);

            TrainPreReserved.Clear();

            foreach (Train.TrainRouted trainRouted in queue)
            {
                Train train      = SignalEnvironment.FindTrain(trainRouted.Train.Number, trains);
                int   routeIndex = trainRouted.TrainRouteDirectionIndex;
                if (train != null)
                {
                    TrainPreReserved.Enqueue(routeIndex == 0 ? train.RoutedForward : train.RoutedBackward);
                }
            }

            // Claimed
            queue = new Queue <Train.TrainRouted>(TrainClaimed);
            TrainClaimed.Clear();

            foreach (Train.TrainRouted trainRouted in queue)
            {
                Train train      = SignalEnvironment.FindTrain(trainRouted.Train.Number, trains);
                int   routeIndex = trainRouted.TrainRouteDirectionIndex;
                if (train != null)
                {
                    TrainClaimed.Enqueue(routeIndex == 0 ? train.RoutedForward : train.RoutedBackward);
                }
            }
        }
 //================================================================================================//
 /// <summary>
 /// check if this train occupies track
 /// unrouted train
 /// </summary>
 public bool OccupiedByThisTrain(Train train)
 {
     return(OccupationState.ContainsTrain(train));
 }
Example #34
0
    /// <summary>
    /// 订单支付银行清单
    /// </summary>
    private void OrderPayPost()
    {
        string session  = Common.utils.NewRequest("session", Common.utils.RequestType.Form);
        string token    = Common.utils.NewRequest("token", Common.utils.RequestType.Form);
        string orderid  = Common.utils.NewRequest("orderid", Common.utils.RequestType.Form);
        string ticketid = Common.utils.NewRequest("ticketid", Common.utils.RequestType.Form);

        string str1 = new Regex(@"JSESSIONID=([^;]*);", RegexOptions.IgnoreCase).Match(session).Groups[1].ToString();
        string str2 = new Regex(@"BIGipServerotsweb=([^;]*);", RegexOptions.IgnoreCase).Match(session).Groups[1].ToString();
        string str  = str1 + "|" + str2;

        string result1 = string.Empty;

        Train  send   = new Train();
        string result = send.SendPayRequest(str, token, orderid, ticketid);



        //File.WriteAllText(Server.MapPath("test111221.txt"), result);

        if (result.IndexOf("该车次在互联网已停止办理业务") == -1)
        {
            //Log(str);
            //第一次支付界面
            string data = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""tranData""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            string msg  = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""merSignMsg""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            result = send.SendPayRequestEpay(str, data, msg);
            //result = result.Replace("</body>", "<script type=\"text/javascript\">formsubmit('00011000');</script></body>");
            //result = result.Replace(",", "").Replace("|", "");
            //File.WriteAllText(Server.MapPath("test1112222.txt"), result);

            //第二次支付界面
            data    = new Regex(@"<input[\s]*type=""hidden""[\s]*value=""([^""]*)""[\s]*name=""tranData"" />", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            msg     = new Regex(@"<input[\s]*type=""hidden""[\s]*value=""([^""]*)""[\s]*name=""merSignMsg"" />", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            orderid = new Regex(@"<input[\s]*type=""hidden""[\s]*value=""([^""]*)""[\s]*name=""orderTimeoutDate"" />", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            //result = send.SendPayRequestEpayStep(data, msg, orderid, str, "00011000");
            //result1 = send.SendPayRequestEpayStep(data, msg, orderid, str, "03080000");

            //招商银行支付
            IDictionary <string, string> param = new Dictionary <string, string>();
            param.Add("tranData", data);
            param.Add("transType", "01");
            param.Add("channelId", "1");
            param.Add("appId", "0001");
            param.Add("merSignMsg", msg);
            param.Add("merCustomIp", "{ip}");
            param.Add("orderTimeoutDate", orderid);
            param.Add("bankId", "03080000");


            //网银直接支付
            IDictionary <string, string> param1 = new Dictionary <string, string>();
            param1.Add("tranData", data);
            param1.Add("transType", "01");
            param1.Add("channelId", "1");
            param1.Add("appId", "0001");
            param1.Add("merSignMsg", msg);
            param1.Add("merCustomIp", "{ip}");
            param1.Add("orderTimeoutDate", orderid);
            param1.Add("bankId", "00011000");
            //result = result.Replace("value=\"01\"", "value=\"05\"");
            //result = result.Replace(",", "").Replace("|", "");
            //result1 = result1.Replace(",", "").Replace("|", "");

            //第三次支付界面
            string time       = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""orderTime""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            string backUrl    = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""backEndUrl""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            string merId      = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""merId""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            string frontUrl   = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""frontEndUrl""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            string signature  = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""signature""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            string amount     = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""orderAmount""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            string mer        = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""merReserved""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            string payorderid = new Regex(@"<input[\s]*type=""hidden""[\s]*name=""orderNumber""[\s]*value=""([^""]*)"">", RegexOptions.IgnoreCase).Match(result).Groups[1].ToString();
            //result = send.SendPayRequestEpayStepNew(time, backUrl, merId, frontUrl, signature, amount, mer, payorderid, str);
            ////File.WriteAllText(Server.MapPath("test1112222344.txt"), result);
            //result = new Regex(@"<form[\s\S]*?</form>", RegexOptions.IgnoreCase).Match(result).Groups[0].ToString();

            string resStr = string.Empty;

            resStr  = @"招商银行*招商银行支付简介*https://epay.12306.cn/pay/webBusiness*" + utils.PostData(param) + "*";
            resStr += "|网银支付(银联)*网银支付(银联)*https://epay.12306.cn/pay/webBusiness*" + utils.PostData(param1) + "*********setTimeout('direct()',10); function direct(){if(document.getElementById('CSPayTab')){window.location.href=document.getElementById('CSPayTab').getAttribute('href');}}";
            resStr += "|建行支付(银联)*建行支付(银联)*https://epay.12306.cn/pay/webBusiness*" + utils.PostData(param1) + "*********setTimeout('direct()',10); function direct(){if(document.getElementById('CSPayTab')){window.location.href=document.getElementById('CSPayTab').getAttribute('href');}}*****setTimeout('direct()',10); function direct(){document.getElementsByName('csBank')[3].checked = true;document.getElementById('csForm').submit();}";

            //File.WriteAllText(Server.MapPath("test11122223.txt"), result);
            Response.Write(resStr);
            Response.End();
        }
        else
        {
            Response.Write(@"该车次在互联网已停止办理业务,该车次在互联网已停止办理业务,该车次在互联网已停止办理业务");
            Response.End();
        }
    }
        public override void onClick(MapViewWindow source, Location loc, Point ab)
        {
            if (isPlacingMode)
            {
                if (this.selectedTrain == null)
                {
                    return;
                }

                // place
                Train tr = this.selectedTrain;
                if (tr.isPlaced)
                {
                    // see if the user has clicked the same train
                    Car c = Car.get(loc);
                    if (c is Train.TrainCar && ((Train.TrainCar)c).parent == tr)
                    {
                        // clicking the same train will be considered to reverse its direction
                        // and change the position of arrow
                        tr.reverse();
                        resetArrowLocation();
                        return;
                    }
                    else
                    {
                        MainWindow.showError("This train is already placed");
                        //; MainWindow.showError("配置済みです");
                        return;
                    }
                }

                RailRoad rr = RailRoad.get(loc);
                if (rr == null)
                {
                    MainWindow.showError("Can not place without tracks");
                    //; MainWindow.showError("線路のないところには配置できません");
                    return;
                }

                if (!tr.place(loc))
                {
                    MainWindow.showError("Can not place");
                    //! MainWindow.showError("配置できません");
                }
                else
                {
                    playSound();
                }
            }
            else
            {
                // remove
                RailRoad rr = RailRoad.get(loc);
                if (rr == null)
                {
                    MainWindow.showError("There are no tracks");
                    //! MainWindow.showError("線路がありません");
                    return;
                }
                if (!(rr.voxel.car is Train.TrainCar))
                {
                    MainWindow.showError("There are no cars");
                    //! MainWindow.showError("車両がありません");
                    return;
                }
                ((Train.TrainCar)rr.voxel.car).parent.remove();
                playSound();
                // successfully removed
            }
        }
Example #36
0
 public static void addTrain(Train train)
 {
     Instance.trains.Add(train);
 }
Example #37
0
        public static string ImportTickets(StationsDbContext context, string xmlString)
        {
            var xmlSerializer       = new XmlSerializer(typeof(TicketDto[]), new XmlRootAttribute("Tickets"));
            var deserializedTickets = (TicketDto[])xmlSerializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));

            var validTickets = new List <Ticket>();

            var sb = new StringBuilder();

            foreach (var ticketDto in deserializedTickets)
            {
                if (!IsValid(ticketDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                DateTime departureTime = DateTime.ParseExact(ticketDto.Trip.DepartureTime, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);

                int?tripId = context.Trips
                             .SingleOrDefault(t => t.OriginStation.Name == ticketDto.Trip.OriginStation &&
                                              t.DestinationStation.Name == ticketDto.Trip.DestinationStation &&
                                              t.DepartureTime == departureTime)?.Id;

                if (tripId == null)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                Train train = context.Trips
                              .Include(t => t.Train)
                              .ThenInclude(t => t.TrainSeats)
                              .ThenInclude(t => t.SeatingClass)
                              .SingleOrDefault(t => t.OriginStation.Name == ticketDto.Trip.OriginStation &&
                                               t.DestinationStation.Name == ticketDto.Trip.DestinationStation &&
                                               t.DepartureTime == departureTime).Train;

                string abbreviation = ticketDto.Seat.Substring(0, 2);

                var seatingClass = train.TrainSeats.SingleOrDefault(t => t.SeatingClass.Abbreviation == abbreviation);

                if (seatingClass == null)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                bool seatsAvailable = train.TrainSeats.Any(t => t.Id == seatingClass.Id);

                if (!seatsAvailable)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                int quantity = int.Parse(ticketDto.Seat.Substring(2, ticketDto.Seat.Length - 2));

                bool seatExists = train.TrainSeats.FirstOrDefault(t => t.Id == seatingClass.Id).Quantity >= quantity;

                int?cardId = null;

                if (ticketDto.Card != null)
                {
                    bool cardExists = context.Cards.AsNoTracking().Any(c => c.Name == ticketDto.Card.Name);

                    if (!cardExists)
                    {
                        sb.AppendLine(FailureMessage);
                        continue;
                    }

                    cardId = context.Cards.AsNoTracking().SingleOrDefault(c => c.Name == ticketDto.Card.Name)?.Id;
                }

                if (!seatExists)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                Ticket ticket = new Ticket
                {
                    TripId         = tripId.Value,
                    CustomerCardId = cardId,
                    Price          = ticketDto.Price,
                    SeatingPlace   = ticketDto.Seat
                };

                validTickets.Add(ticket);

                sb.AppendLine($"Ticket from {ticketDto.Trip.OriginStation} to {ticketDto.Trip.DestinationStation} departing at {departureTime.ToString("dd/MM/yyyy HH:mm")} imported.");
            }

            context.Tickets.AddRange(validTickets);
            context.SaveChanges();

            string result = sb.ToString().TrimEnd();

            return(result);
        }
Example #38
0
 public static int Comp(Train t1, Train t2)
 {
     return(t1.num.CompareTo(t2.num));
 }
Example #39
0
 /// <summary>Moves the air brake handle to the specified state</summary>
 /// <param name="Train">The train</param>
 /// <param name="State">The state</param>
 internal static void ApplyAirBrakeHandle(Train Train, AirBrakeHandleState State)
 {
     if (Train.Cars[Train.DriverCar].Specs.BrakeType == CarBrakeType.AutomaticAirBrake)
     {
         if (State != Train.Specs.AirBrake.Handle.Driver)
         {
             // sound when moved to service
             if (State == AirBrakeHandleState.Service)
             {
                 Sounds.SoundBuffer buffer = Train.Cars[Train.DriverCar].Sounds.Brake.Buffer;
                 if (buffer != null)
                 {
                     OpenBveApi.Math.Vector3 pos = Train.Cars[Train.DriverCar].Sounds.Brake.Position;
                     Sounds.PlaySound(buffer, 1.0, 1.0, pos, Train, Train.DriverCar, false);
                 }
             }
             // sound
             if ((int)State < (int)Train.Specs.AirBrake.Handle.Driver)
             {
                 // brake release
                 if ((int)State > 0)
                 {
                     // brake release (not min)
                     Sounds.SoundBuffer buffer = Train.Cars[Train.DriverCar].Sounds.BrakeHandleRelease.Buffer;
                     if (buffer != null)
                     {
                         OpenBveApi.Math.Vector3 pos = Train.Cars[Train.DriverCar].Sounds.BrakeHandleRelease.Position;
                         Sounds.PlaySound(buffer, 1.0, 1.0, pos, Train, Train.DriverCar, false);
                     }
                 }
                 else
                 {
                     // brake min
                     Sounds.SoundBuffer buffer = Train.Cars[Train.DriverCar].Sounds.BrakeHandleMin.Buffer;
                     if (buffer != null)
                     {
                         OpenBveApi.Math.Vector3 pos = Train.Cars[Train.DriverCar].Sounds.BrakeHandleMin.Position;
                         Sounds.PlaySound(buffer, 1.0, 1.0, pos, Train, Train.DriverCar, false);
                     }
                 }
             }
             else if ((int)State > (int)Train.Specs.AirBrake.Handle.Driver)
             {
                 // brake
                 Sounds.SoundBuffer buffer = Train.Cars[Train.DriverCar].Sounds.BrakeHandleApply.Buffer;
                 if (buffer != null)
                 {
                     OpenBveApi.Math.Vector3 pos = Train.Cars[Train.DriverCar].Sounds.BrakeHandleApply.Position;
                     Sounds.PlaySound(buffer, 1.0, 1.0, pos, Train, Train.DriverCar, false);
                 }
             }
             // apply
             Train.Specs.AirBrake.Handle.Driver = State;
             Game.AddBlackBoxEntry(Game.BlackBoxEventToken.None);
             // plugin
             if (Train.Plugin != null)
             {
                 Train.Plugin.UpdatePower();
                 Train.Plugin.UpdateBrake();
             }
         }
     }
 }
Example #40
0
        /// <summary>Attempts to load and parse the current train's panel configuration file.</summary>
        /// <param name="TrainPath">The absolute on-disk path to the train folder.</param>
        /// <param name="Encoding">The automatically detected or manually set encoding of the panel configuration file.</param>
        /// <param name="Train">The base train on which to apply the panel configuration.</param>
        internal static void ParsePanelConfig(string TrainPath, System.Text.Encoding Encoding, Train Train)
        {
            Train.Cars[Train.DriverCar].CarSections    = new CarSection[1];
            Train.Cars[Train.DriverCar].CarSections[0] = new CarSection
            {
                Groups = new ElementsGroup[1]
            };
            Train.Cars[Train.DriverCar].CarSections[0].Groups[0] = new ElementsGroup
            {
                Elements = new AnimatedObject[] { },
                Overlay  = true
            };
            string File = OpenBveApi.Path.CombineFile(TrainPath, "panel.xml");

            if (!System.IO.File.Exists(File))
            {
                //Try animated variant too
                File = OpenBveApi.Path.CombineFile(TrainPath, "panel.animated.xml");
            }
            if (System.IO.File.Exists(File))
            {
                Program.FileSystem.AppendToLogFile("Loading train panel: " + File);
                try
                {
                    /*
                     * First load the XML. We use this to determine
                     * whether this is a 2D or a 3D animated panel
                     */
                    XDocument CurrentXML = XDocument.Load(File, LoadOptions.SetLineInfo);

                    // Check for null
                    if (CurrentXML.Root != null)
                    {
                        IEnumerable <XElement> DocumentElements = CurrentXML.Root.Elements("PanelAnimated");
                        if (DocumentElements.Any())
                        {
                            PanelAnimatedXmlParser.ParsePanelAnimatedXml(System.IO.Path.GetFileName(File), TrainPath, Train, Train.DriverCar);
                            if (Train.Cars[Train.DriverCar].CameraRestrictionMode != CameraRestrictionMode.Restricted3D)
                            {
                                Train.Cars[Train.DriverCar].CameraRestrictionMode = CameraRestrictionMode.NotAvailable;
                            }
                        }

                        DocumentElements = CurrentXML.Root.Elements("Panel");
                        if (DocumentElements.Any())
                        {
                            PanelXmlParser.ParsePanelXml(System.IO.Path.GetFileName(File), TrainPath, Train, Train.DriverCar);
                            Train.Cars[Train.DriverCar].CameraRestrictionMode = CameraRestrictionMode.On;
                            Program.Renderer.Camera.CurrentRestriction        = CameraRestrictionMode.On;
                        }
                    }
                }
                catch
                {
                    var currentError = Translations.GetInterfaceString("errors_critical_file");
                    currentError = currentError.Replace("[file]", "panel.xml");
                    MessageBox.Show(currentError, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    Program.RestartArguments = " ";
                    Loading.Cancel           = true;
                    return;
                }

                if (Train.Cars[Train.DriverCar].CarSections[0].Groups[0].Elements.Any())
                {
                    OpenBVEGame.RunInRenderThread(() =>
                    {
                        //Needs to be on the thread containing the openGL context
                        Program.Renderer.InitializeVisibility();
                    });
                    World.UpdateViewingDistances();
                    return;
                }
                Interface.AddMessage(MessageType.Error, false, "The panel.xml file " + File + " failed to load. Falling back to legacy panel.");
            }
            else
            {
                File = OpenBveApi.Path.CombineFile(TrainPath, "panel.animated");
                if (System.IO.File.Exists(File))
                {
                    Program.FileSystem.AppendToLogFile("Loading train panel: " + File);
                    if (System.IO.File.Exists(OpenBveApi.Path.CombineFile(TrainPath, "panel2.cfg")) || System.IO.File.Exists(OpenBveApi.Path.CombineFile(TrainPath, "panel.cfg")))
                    {
                        Program.FileSystem.AppendToLogFile("INFO: This train contains both a 2D and a 3D panel. The 3D panel will always take precedence");
                    }

                    UnifiedObject currentObject;
                    Program.CurrentHost.LoadObject(File, Encoding, out currentObject);
                    var a = currentObject as AnimatedObjectCollection;
                    if (a != null)
                    {
                        //HACK: If a == null , loading our animated object completely failed (Missing objects?). Fallback to trying the panel2.cfg
                        try
                        {
                            for (int i = 0; i < a.Objects.Length; i++)
                            {
                                Program.CurrentHost.CreateDynamicObject(ref a.Objects[i].internalObject);
                            }
                            Train.Cars[Train.DriverCar].CarSections[0].Groups[0].Elements = a.Objects;
                            if (Train.Cars[Train.DriverCar].CameraRestrictionMode != CameraRestrictionMode.Restricted3D)
                            {
                                Train.Cars[Train.DriverCar].CameraRestrictionMode = CameraRestrictionMode.NotAvailable;
                                Program.Renderer.Camera.CurrentRestriction        = CameraRestrictionMode.NotAvailable;
                            }
                            World.UpdateViewingDistances();
                            return;
                        }
                        catch
                        {
                            var currentError = Translations.GetInterfaceString("errors_critical_file");
                            currentError = currentError.Replace("[file]", "panel.animated");
                            MessageBox.Show(currentError, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            Program.RestartArguments = " ";
                            Loading.Cancel           = true;
                            return;
                        }
                    }
                    Interface.AddMessage(MessageType.Error, false, "The panel.animated file " + File + " failed to load. Falling back to 2D panel.");
                }
            }

            var Panel2 = false;

            try
            {
                File = OpenBveApi.Path.CombineFile(TrainPath, "panel2.cfg");
                if (System.IO.File.Exists(File))
                {
                    Program.FileSystem.AppendToLogFile("Loading train panel: " + File);
                    Panel2 = true;
                    Panel2CfgParser.ParsePanel2Config("panel2.cfg", TrainPath, Train, Train.DriverCar);
                    Train.Cars[Train.DriverCar].CameraRestrictionMode = CameraRestrictionMode.On;
                    Program.Renderer.Camera.CurrentRestriction        = CameraRestrictionMode.On;
                }
                else
                {
                    File = OpenBveApi.Path.CombineFile(TrainPath, "panel.cfg");
                    if (System.IO.File.Exists(File))
                    {
                        Program.FileSystem.AppendToLogFile("Loading train panel: " + File);
                        PanelCfgParser.ParsePanelConfig(TrainPath, Encoding, Train);
                        Train.Cars[Train.DriverCar].CameraRestrictionMode = CameraRestrictionMode.On;
                        Program.Renderer.Camera.CurrentRestriction        = CameraRestrictionMode.On;
                    }
                    else
                    {
                        Program.Renderer.Camera.CurrentRestriction = CameraRestrictionMode.NotAvailable;
                    }
                }
            }
            catch
            {
                var currentError = Translations.GetInterfaceString("errors_critical_file");
                currentError = currentError.Replace("[file]", Panel2 ? "panel2.cfg" : "panel.cfg");
                MessageBox.Show(currentError, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Program.RestartArguments = " ";
                Loading.Cancel           = true;
            }
        }
Example #41
0
        /// <summary>This method should be called once a frame to update the position, speed and state of all trains within the simulation</summary>
        /// <param name="TimeElapsed">The time elapsed since the last call to this function</param>
        internal static void UpdateTrains(double TimeElapsed)
        {
            for (int i = 0; i < Trains.Length; i++)
            {
                Trains[i].Update(TimeElapsed);
            }

            foreach (var Train in TFOs)
            {
                Train.Update(TimeElapsed);
            }

            // detect collision
            if (!Game.MinimalisticSimulation & Interface.CurrentOptions.Collisions)
            {
                //for (int i = 0; i < Trains.Length; i++) {
                System.Threading.Tasks.Parallel.For(0, Trains.Length, i =>
                {
                    // with other trains
                    if (Trains[i].State == TrainState.Available)
                    {
                        double a = Trains[i].FrontCarTrackPosition();
                        double b = Trains[i].RearCarTrackPosition();
                        for (int j = i + 1; j < Trains.Length; j++)
                        {
                            if (Trains[j].State == TrainState.Available)
                            {
                                double c = Trains[j].FrontCarTrackPosition();
                                double d = Trains[j].RearCarTrackPosition();
                                if (a > d & b < c)
                                {
                                    if (a > c)
                                    {
                                        // i > j
                                        int k = Trains[i].Cars.Length - 1;
                                        if (Trains[i].Cars[k].CurrentSpeed < Trains[j].Cars[0].CurrentSpeed)
                                        {
                                            double v = Trains[j].Cars[0].CurrentSpeed - Trains[i].Cars[k].CurrentSpeed;
                                            double s = (Trains[i].Cars[k].CurrentSpeed * Trains[i].Cars[k].Specs.MassCurrent +
                                                        Trains[j].Cars[0].CurrentSpeed * Trains[j].Cars[0].Specs.MassCurrent) /
                                                       (Trains[i].Cars[k].Specs.MassCurrent + Trains[j].Cars[0].Specs.MassCurrent);
                                            Trains[i].Cars[k].CurrentSpeed = s;
                                            Trains[j].Cars[0].CurrentSpeed = s;
                                            double e = 0.5 * (c - b) + 0.0001;
                                            Trains[i].Cars[k].FrontAxle.Follower.UpdateRelative(e, false, false);
                                            Trains[i].Cars[k].RearAxle.Follower.UpdateRelative(e, false, false);
                                            Trains[j].Cars[0].FrontAxle.Follower.UpdateRelative(-e, false, false);

                                            Trains[j].Cars[0].RearAxle.Follower.UpdateRelative(-e, false, false);
                                            if (Interface.CurrentOptions.Derailments)
                                            {
                                                double f  = 2.0 / (Trains[i].Cars[k].Specs.MassCurrent + Trains[j].Cars[0].Specs.MassCurrent);
                                                double fi = Trains[j].Cars[0].Specs.MassCurrent * f;
                                                double fj = Trains[i].Cars[k].Specs.MassCurrent * f;
                                                double vi = v * fi;
                                                double vj = v * fj;
                                                if (vi > Trains[i].CriticalCollisionSpeedDifference)
                                                {
                                                    Trains[i].Derail(k, TimeElapsed);
                                                }
                                                if (vj > Trains[j].CriticalCollisionSpeedDifference)
                                                {
                                                    Trains[j].Derail(i, TimeElapsed);
                                                }
                                            }
                                            // adjust cars for train i
                                            for (int h = Trains[i].Cars.Length - 2; h >= 0; h--)
                                            {
                                                a = Trains[i].Cars[h + 1].FrontAxle.Follower.TrackPosition -
                                                    Trains[i].Cars[h + 1].FrontAxle.Position + 0.5 * Trains[i].Cars[h + 1].Length;
                                                b = Trains[i].Cars[h].RearAxle.Follower.TrackPosition -
                                                    Trains[i].Cars[h].RearAxle.Position - 0.5 * Trains[i].Cars[h].Length;
                                                d = b - a - Trains[i].Cars[h].Coupler.MinimumDistanceBetweenCars;
                                                if (d < 0.0)
                                                {
                                                    d -= 0.0001;
                                                    Trains[i].Cars[h].FrontAxle.Follower.UpdateRelative(-d, false, false);
                                                    Trains[i].Cars[h].RearAxle.Follower.UpdateRelative(-d, false, false);
                                                    if (Interface.CurrentOptions.Derailments)
                                                    {
                                                        double f  = 2.0 / (Trains[i].Cars[h + 1].Specs.MassCurrent + Trains[i].Cars[h].Specs.MassCurrent);
                                                        double fi = Trains[i].Cars[h + 1].Specs.MassCurrent * f;
                                                        double fj = Trains[i].Cars[h].Specs.MassCurrent * f;
                                                        double vi = v * fi;
                                                        double vj = v * fj;
                                                        if (vi > Trains[i].CriticalCollisionSpeedDifference)
                                                        {
                                                            Trains[i].Derail(h + 1, TimeElapsed);
                                                        }
                                                        if (vj > Trains[j].CriticalCollisionSpeedDifference)
                                                        {
                                                            Trains[i].Derail(h, TimeElapsed);
                                                        }
                                                    }
                                                    Trains[i].Cars[h].CurrentSpeed =
                                                        Trains[i].Cars[h + 1].CurrentSpeed;
                                                }
                                            }
                                            // adjust cars for train j
                                            for (int h = 1; h < Trains[j].Cars.Length; h++)
                                            {
                                                a = Trains[j].Cars[h - 1].RearAxle.Follower.TrackPosition -
                                                    Trains[j].Cars[h - 1].RearAxle.Position - 0.5 * Trains[j].Cars[h - 1].Length;
                                                b = Trains[j].Cars[h].FrontAxle.Follower.TrackPosition -
                                                    Trains[j].Cars[h].FrontAxle.Position + 0.5 * Trains[j].Cars[h].Length;
                                                d = a - b - Trains[j].Cars[h - 1].Coupler.MinimumDistanceBetweenCars;
                                                if (d < 0.0)
                                                {
                                                    d -= 0.0001;
                                                    Trains[j].Cars[h].FrontAxle.Follower.UpdateRelative(d, false, false);
                                                    Trains[j].Cars[h].RearAxle.Follower.UpdateRelative(d, false, false);
                                                    if (Interface.CurrentOptions.Derailments)
                                                    {
                                                        double f  = 2.0 / (Trains[j].Cars[h - 1].Specs.MassCurrent + Trains[j].Cars[h].Specs.MassCurrent);
                                                        double fi = Trains[j].Cars[h - 1].Specs.MassCurrent * f;
                                                        double fj = Trains[j].Cars[h].Specs.MassCurrent * f;
                                                        double vi = v * fi;
                                                        double vj = v * fj;
                                                        if (vi > Trains[j].CriticalCollisionSpeedDifference)
                                                        {
                                                            Trains[j].Derail(h - 1, TimeElapsed);
                                                        }
                                                        if (vj > Trains[j].CriticalCollisionSpeedDifference)
                                                        {
                                                            Trains[j].Derail(h, TimeElapsed);
                                                        }
                                                    }
                                                    Trains[j].Cars[h].CurrentSpeed =
                                                        Trains[j].Cars[h - 1].CurrentSpeed;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // i < j
                                        int k = Trains[j].Cars.Length - 1;
                                        if (Trains[i].Cars[0].CurrentSpeed > Trains[j].Cars[k].CurrentSpeed)
                                        {
                                            double v = Trains[i].Cars[0].CurrentSpeed -
                                                       Trains[j].Cars[k].CurrentSpeed;
                                            double s = (Trains[i].Cars[0].CurrentSpeed * Trains[i].Cars[0].Specs.MassCurrent +
                                                        Trains[j].Cars[k].CurrentSpeed * Trains[j].Cars[k].Specs.MassCurrent) /
                                                       (Trains[i].Cars[0].Specs.MassCurrent + Trains[j].Cars[k].Specs.MassCurrent);
                                            Trains[i].Cars[0].CurrentSpeed = s;
                                            Trains[j].Cars[k].CurrentSpeed = s;
                                            double e = 0.5 * (a - d) + 0.0001;
                                            Trains[i].Cars[0].FrontAxle.Follower.UpdateRelative(-e, false, false);
                                            Trains[i].Cars[0].RearAxle.Follower.UpdateRelative(-e, false, false);
                                            Trains[j].Cars[k].FrontAxle.Follower.UpdateRelative(e, false, false);
                                            Trains[j].Cars[k].RearAxle.Follower.UpdateRelative(e, false, false);
                                            if (Interface.CurrentOptions.Derailments)
                                            {
                                                double f  = 2.0 / (Trains[i].Cars[0].Specs.MassCurrent + Trains[j].Cars[k].Specs.MassCurrent);
                                                double fi = Trains[j].Cars[k].Specs.MassCurrent * f;
                                                double fj = Trains[i].Cars[0].Specs.MassCurrent * f;
                                                double vi = v * fi;
                                                double vj = v * fj;
                                                if (vi > Trains[i].CriticalCollisionSpeedDifference)
                                                {
                                                    Trains[i].Derail(0, TimeElapsed);
                                                }
                                                if (vj > Trains[j].CriticalCollisionSpeedDifference)
                                                {
                                                    Trains[j].Derail(k, TimeElapsed);
                                                }
                                            }
                                            // adjust cars for train i
                                            for (int h = 1; h < Trains[i].Cars.Length; h++)
                                            {
                                                a = Trains[i].Cars[h - 1].RearAxle.Follower.TrackPosition -
                                                    Trains[i].Cars[h - 1].RearAxle.Position - 0.5 * Trains[i].Cars[h - 1].Length;
                                                b = Trains[i].Cars[h].FrontAxle.Follower.TrackPosition -
                                                    Trains[i].Cars[h].FrontAxle.Position + 0.5 * Trains[i].Cars[h].Length;
                                                d = a - b - Trains[i].Cars[h - 1].Coupler.MinimumDistanceBetweenCars;
                                                if (d < 0.0)
                                                {
                                                    d -= 0.0001;
                                                    Trains[i].Cars[h].FrontAxle.Follower.UpdateRelative(d, false, false);
                                                    Trains[i].Cars[h].RearAxle.Follower.UpdateRelative(d, false, false);
                                                    if (Interface.CurrentOptions.Derailments)
                                                    {
                                                        double f  = 2.0 / (Trains[i].Cars[h - 1].Specs.MassCurrent + Trains[i].Cars[h].Specs.MassCurrent);
                                                        double fi = Trains[i].Cars[h - 1].Specs.MassCurrent * f;
                                                        double fj = Trains[i].Cars[h].Specs.MassCurrent * f;
                                                        double vi = v * fi;
                                                        double vj = v * fj;
                                                        if (vi > Trains[i].CriticalCollisionSpeedDifference)
                                                        {
                                                            Trains[i].Derail(h - 1, TimeElapsed);
                                                        }
                                                        if (vj > Trains[i].CriticalCollisionSpeedDifference)
                                                        {
                                                            Trains[i].Derail(h, TimeElapsed);
                                                        }
                                                    }
                                                    Trains[i].Cars[h].CurrentSpeed =
                                                        Trains[i].Cars[h - 1].CurrentSpeed;
                                                }
                                            }
                                            // adjust cars for train j
                                            for (int h = Trains[j].Cars.Length - 2; h >= 0; h--)
                                            {
                                                a = Trains[j].Cars[h + 1].FrontAxle.Follower.TrackPosition -
                                                    Trains[j].Cars[h + 1].FrontAxle.Position + 0.5 * Trains[j].Cars[h + 1].Length;
                                                b = Trains[j].Cars[h].RearAxle.Follower.TrackPosition -
                                                    Trains[j].Cars[h].RearAxle.Position - 0.5 * Trains[j].Cars[h].Length;
                                                d = b - a - Trains[j].Cars[h].Coupler.MinimumDistanceBetweenCars;
                                                if (d < 0.0)
                                                {
                                                    d -= 0.0001;
                                                    Trains[j].Cars[h].FrontAxle.Follower.UpdateRelative(-d, false, false);
                                                    Trains[j].Cars[h].RearAxle.Follower.UpdateRelative(-d, false, false);
                                                    if (Interface.CurrentOptions.Derailments)
                                                    {
                                                        double f  = 2.0 / (Trains[j].Cars[h + 1].Specs.MassCurrent + Trains[j].Cars[h].Specs.MassCurrent);
                                                        double fi = Trains[j].Cars[h + 1].Specs.MassCurrent * f;
                                                        double fj = Trains[j].Cars[h].Specs.MassCurrent * f;
                                                        double vi = v * fi;
                                                        double vj = v * fj;
                                                        if (vi > Trains[i].CriticalCollisionSpeedDifference)
                                                        {
                                                            Trains[j].Derail(h + 1, TimeElapsed);
                                                        }
                                                        if (vj > Trains[j].CriticalCollisionSpeedDifference)
                                                        {
                                                            Trains[j].Derail(h, TimeElapsed);
                                                        }
                                                    }
                                                    Trains[j].Cars[h].CurrentSpeed =
                                                        Trains[j].Cars[h + 1].CurrentSpeed;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // with buffers
                    if (Trains[i].IsPlayerTrain)
                    {
                        double a = Trains[i].Cars[0].FrontAxle.Follower.TrackPosition - Trains[i].Cars[0].FrontAxle.Position +
                                   0.5 * Trains[i].Cars[0].Length;
                        double b = Trains[i].Cars[Trains[i].Cars.Length - 1].RearAxle.Follower.TrackPosition -
                                   Trains[i].Cars[Trains[i].Cars.Length - 1].RearAxle.Position - 0.5 * Trains[i].Cars[0].Length;
                        for (int j = 0; j < Program.CurrentRoute.BufferTrackPositions.Length; j++)
                        {
                            if (a > Program.CurrentRoute.BufferTrackPositions[j] & b < Program.CurrentRoute.BufferTrackPositions[j])
                            {
                                a        += 0.0001;
                                b        -= 0.0001;
                                double da = a - Program.CurrentRoute.BufferTrackPositions[j];
                                double db = Program.CurrentRoute.BufferTrackPositions[j] - b;
                                if (da < db)
                                {
                                    // front
                                    Trains[i].Cars[0].UpdateTrackFollowers(-da, false, false);
                                    if (Interface.CurrentOptions.Derailments &&
                                        Math.Abs(Trains[i].Cars[0].CurrentSpeed) > Trains[i].CriticalCollisionSpeedDifference)
                                    {
                                        Trains[i].Derail(0, TimeElapsed);
                                    }
                                    Trains[i].Cars[0].CurrentSpeed = 0.0;
                                    for (int h = 1; h < Trains[i].Cars.Length; h++)
                                    {
                                        a = Trains[i].Cars[h - 1].RearAxle.Follower.TrackPosition -
                                            Trains[i].Cars[h - 1].RearAxle.Position - 0.5 * Trains[i].Cars[h - 1].Length;
                                        b = Trains[i].Cars[h].FrontAxle.Follower.TrackPosition -
                                            Trains[i].Cars[h].FrontAxle.Position + 0.5 * Trains[i].Cars[h].Length;
                                        double d = a - b - Trains[i].Cars[h - 1].Coupler.MinimumDistanceBetweenCars;
                                        if (d < 0.0)
                                        {
                                            d -= 0.0001;
                                            Trains[i].Cars[h].UpdateTrackFollowers(d, false, false);
                                            if (Interface.CurrentOptions.Derailments &&
                                                Math.Abs(Trains[i].Cars[h].CurrentSpeed) >
                                                Trains[j].CriticalCollisionSpeedDifference)
                                            {
                                                Trains[i].Derail(h, TimeElapsed);
                                            }
                                            Trains[i].Cars[h].CurrentSpeed = 0.0;
                                        }
                                    }
                                }
                                else
                                {
                                    // rear
                                    int c = Trains[i].Cars.Length - 1;
                                    Trains[i].Cars[c].UpdateTrackFollowers(db, false, false);
                                    if (Interface.CurrentOptions.Derailments &&
                                        Math.Abs(Trains[i].Cars[c].CurrentSpeed) > Trains[i].CriticalCollisionSpeedDifference)
                                    {
                                        Trains[i].Derail(c, TimeElapsed);
                                    }
                                    Trains[i].Cars[c].CurrentSpeed = 0.0;
                                    for (int h = Trains[i].Cars.Length - 2; h >= 0; h--)
                                    {
                                        a = Trains[i].Cars[h + 1].FrontAxle.Follower.TrackPosition -
                                            Trains[i].Cars[h + 1].FrontAxle.Position + 0.5 * Trains[i].Cars[h + 1].Length;
                                        b = Trains[i].Cars[h].RearAxle.Follower.TrackPosition -
                                            Trains[i].Cars[h].RearAxle.Position - 0.5 * Trains[i].Cars[h].Length;
                                        double d = b - a - Trains[i].Cars[h].Coupler.MinimumDistanceBetweenCars;
                                        if (d < 0.0)
                                        {
                                            d -= 0.0001;
                                            Trains[i].Cars[h].UpdateTrackFollowers(-d, false, false);
                                            if (Interface.CurrentOptions.Derailments &&
                                                Math.Abs(Trains[i].Cars[h].CurrentSpeed) >
                                                Trains[i].CriticalCollisionSpeedDifference)
                                            {
                                                Trains[i].Derail(h, TimeElapsed);
                                            }
                                            Trains[i].Cars[h].CurrentSpeed = 0.0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            }
            // compute final angles and positions
            //for (int i = 0; i < Trains.Length; i++) {
            System.Threading.Tasks.Parallel.For(0, Trains.Length, i =>
            {
                if (Trains[i].State != TrainState.Disposed & Trains[i].State != TrainState.Bogus)
                {
                    for (int j = 0; j < Trains[i].Cars.Length; j++)
                    {
                        Trains[i].Cars[j].FrontAxle.Follower.UpdateWorldCoordinates(true);
                        Trains[i].Cars[j].FrontBogie.FrontAxle.Follower.UpdateWorldCoordinates(true);
                        Trains[i].Cars[j].FrontBogie.RearAxle.Follower.UpdateWorldCoordinates(true);
                        Trains[i].Cars[j].RearAxle.Follower.UpdateWorldCoordinates(true);
                        Trains[i].Cars[j].RearBogie.FrontAxle.Follower.UpdateWorldCoordinates(true);
                        Trains[i].Cars[j].RearBogie.RearAxle.Follower.UpdateWorldCoordinates(true);
                        if (TimeElapsed == 0.0 | TimeElapsed > 0.5)
                        {
                            //Don't update the toppling etc. with excessive or no time
                            continue;
                        }
                        Trains[i].Cars[j].UpdateTopplingCantAndSpring(TimeElapsed);
                        Trains[i].Cars[j].FrontBogie.UpdateTopplingCantAndSpring();
                        Trains[i].Cars[j].RearBogie.UpdateTopplingCantAndSpring();
                    }
                }
            });

            System.Threading.Tasks.Parallel.For(0, TFOs.Length, i =>
            {
                if (TFOs[i].State != TrainState.Disposed & TFOs[i].State != TrainState.Bogus)
                {
                    foreach (var Car in TFOs[i].Cars)
                    {
                        Car.FrontAxle.Follower.UpdateWorldCoordinates(true);
                        Car.FrontBogie.FrontAxle.Follower.UpdateWorldCoordinates(true);
                        Car.FrontBogie.RearAxle.Follower.UpdateWorldCoordinates(true);
                        Car.RearAxle.Follower.UpdateWorldCoordinates(true);
                        Car.RearBogie.FrontAxle.Follower.UpdateWorldCoordinates(true);
                        Car.RearBogie.RearAxle.Follower.UpdateWorldCoordinates(true);
                        if (TimeElapsed == 0.0 | TimeElapsed > 0.5)
                        {
                            //Don't update the toppling etc. with excessive or no time
                            continue;
                        }
                        Car.UpdateTopplingCantAndSpring(TimeElapsed);
                        Car.FrontBogie.UpdateTopplingCantAndSpring();
                        Car.RearBogie.UpdateTopplingCantAndSpring();
                    }
                }
            });
        }
Example #42
0
 void Awake()
 {
     train         = FindObjectOfType <Train>();
     movingObjects = FindObjectOfType <MovingObjects>();
 }
 public void enter(Train train)
 {
     this.train = train;
 }
Example #44
0
 public TrainRun(Train train)
 {
     ServiceIntentionId = train.Id;
 }
Example #45
0
    //添加联系人
    private void PersonActPost(string act)
    {
        string session = Common.utils.NewRequest("session", Common.utils.RequestType.Form);

        string name           = Common.utils.NewRequest("name", Common.utils.RequestType.Form);
        string sex            = Common.utils.NewRequest("sex", Common.utils.RequestType.Form);
        string card_type      = Common.utils.NewRequest("card_type", Common.utils.RequestType.Form);
        string card_no        = Common.utils.NewRequest("card_no", Common.utils.RequestType.Form);
        string passenger_type = Common.utils.NewRequest("passenger_type", Common.utils.RequestType.Form);
        string mobile         = Common.utils.NewRequest("mobile", Common.utils.RequestType.Form);

        string str1 = new Regex(@"JSESSIONID=([^;]*);", RegexOptions.IgnoreCase).Match(session).Groups[1].ToString();
        string str2 = new Regex(@"BIGipServerotsweb=([^;]*);", RegexOptions.IgnoreCase).Match(session).Groups[1].ToString();
        string str  = str1 + "|" + str2;

        //根据动作操作会员联系人
        if (act == "add")
        {
            Train  send   = new Train();
            string result = send.SendAddRequest(str, name, sex, card_type, card_no, passenger_type, mobile);

            Response.Write("ok");
            //File.WriteAllText(Server.MapPath("token0.txt"), result);
            Response.End();
            return;
        }

        //根据动作操作会员联系人
        if (act == "edit")
        {
            Train  send   = new Train();
            string result = send.SendEditRequest(str, name, sex, card_type, card_no, passenger_type, mobile);

            //File.WriteAllText(Server.MapPath("token1.txt"), result);
            Response.Write("ok");
            Response.End();
            return;
        }

        //根据动作操作会员联系人
        if (act == "del")
        {
            ////File.WriteAllText(Server.MapPath("token.txt"), "");
            Train  send   = new Train();
            string result = send.SendDelRequest(str, name, sex, card_type, card_no, passenger_type, mobile);
            ////File.WriteAllText(Server.MapPath("token1.txt"), "");

            Response.Write("ok");
            //File.WriteAllText(Server.MapPath("token2.txt"), result);
            Response.End();
            return;
        }

        //根据动作操作会员联系人
        if (act == "search")
        {
            Train  send   = new Train();
            string result = send.SendSearchRequest(str);

            result = result.Replace("null", "\"null\"");

            Response.Write(result);
            Response.End();
            return;
        }
    }
Example #46
0
        /// <summary>
        ///     Displays the graph
        /// </summary>
        /// <returns></returns>
        public void Display()
        {
            Util.DontNotify(() =>
            {
                GraphVisualiser.Reset();
                String name = null;

                // Computes the expected end to display
                double expectedEndX = 0;
                Dictionary <Function, Graph> graphs = new Dictionary <Function, Graph>();
                foreach (Function function in Functions)
                {
                    InterpretationContext context = new InterpretationContext(function);
                    if (function.FormalParameters.Count == 1)
                    {
                        Parameter parameter = (Parameter)function.FormalParameters[0];
                        Graph graph         = function.CreateGraph(context, parameter, null);
                        if (graph != null)
                        {
                            expectedEndX = Math.Max(expectedEndX, graph.ExpectedEndX());
                            graphs.Add(function, graph);
                        }
                    }
                }

                double expectedEndY = 0;
                Dictionary <Function, Surface> surfaces = new Dictionary <Function, Surface>();
                foreach (Function function in Functions)
                {
                    InterpretationContext context = new InterpretationContext(function);
                    if (function.FormalParameters.Count == 2)
                    {
                        Surface surface = function.CreateSurface(context, null);
                        if (surface != null)
                        {
                            expectedEndX = Math.Max(expectedEndX, surface.ExpectedEndX());
                            expectedEndY = Math.Max(expectedEndY, surface.ExpectedEndY());
                            surfaces.Add(function, surface);
                        }
                    }
                }

                try
                {
                    int maxX     = Int32.Parse(Tb_MaxX.Text);
                    expectedEndX = Math.Min(expectedEndX, maxX);
                }
                catch (Exception)
                {
                }

                // Creates the graphs
                foreach (KeyValuePair <Function, Graph> pair in graphs)
                {
                    Function function = pair.Key;
                    Graph graph       = pair.Value;

                    if (function != null && graph != null)
                    {
                        EfsProfileFunction efsProfileFunction = new EfsProfileFunction(graph);
                        if (function.Name.Contains("Gradient"))
                        {
                            GraphVisualiser.AddGraph(new EfsGradientProfileGraph(GraphVisualiser, efsProfileFunction,
                                                                                 function.FullName));
                        }
                        else
                        {
                            GraphVisualiser.AddGraph(new EfsProfileFunctionGraph(GraphVisualiser, efsProfileFunction,
                                                                                 function.FullName));
                        }

                        if (name == null)
                        {
                            name = function.Name;
                        }
                    }
                }

                // Creates the surfaces
                foreach (KeyValuePair <Function, Surface> pair in surfaces)
                {
                    Function function = pair.Key;
                    Surface surface   = pair.Value;

                    if (surface != null)
                    {
                        EfsSurfaceFunction efsSurfaceFunction = new EfsSurfaceFunction(surface);
                        GraphVisualiser.AddGraph(new EfsSurfaceFunctionGraph(GraphVisualiser, efsSurfaceFunction,
                                                                             function.FullName));
                        if (name == null)
                        {
                            name = function.Name;
                        }
                    }
                }

                Train train = new Train(GraphVisualiser);
                train.InitializeTrain(TrainPosition.GetDistance(), TrainPosition.GetSpeed(), TrainPosition.GetUnderReadingAmount(), TrainPosition.GetOverReadingAmount());
                GraphVisualiser.AddGraph(train);
                GraphVisualiser.Annotations.Add(train.TrainLineAnnotation);
                GraphVisualiser.Annotations.Add(train.TrainAnnotation);

                if (name != null)
                {
                    try
                    {
                        double val = double.Parse(Tb_MinX.Text);
                        GraphVisualiser.SetMinX(val);
                    }
                    catch (Exception)
                    {
                    }

                    try
                    {
                        double val = double.Parse(Tb_MaxX.Text);
                        GraphVisualiser.SetMaxX(val);
                    }
                    catch (Exception)
                    {
                    }

                    if (Cb_AutoYSize.Checked)
                    {
                        GraphVisualiser.SetMaxY(double.NaN);
                    }
                    else
                    {
                        double height;
                        if (double.TryParse(Tb_MaxY.Text, out height))
                        {
                            GraphVisualiser.SetMaxY(height);
                        }
                        else
                        {
                            GraphVisualiser.SetMaxY(double.NaN);
                        }
                    }

                    GraphVisualiser.SetMinY2(double.NaN);
                    GraphVisualiser.SetMaxY2(double.NaN);
                    double top, bottom;
                    if (double.TryParse(Tb_MinGrad.Text, out bottom))
                    {
                        GraphVisualiser.SetMinY2(bottom);
                    }
                    if (double.TryParse(Tb_MaxGrad.Text, out top))
                    {
                        GraphVisualiser.SetMaxY2(top);
                    }

                    GraphVisualiser.DrawGraphs(expectedEndX);
                }
            });
        }
Example #47
0
 internal void SetPickList(DominoList list)
 {
     _list  = list;
     _train = new Train(true, list.FirstDouble, this);
 }
Example #48
0
        static void Main(string[] args)
        {
            FileStream xmlStream   = new FileStream("trains.xml", FileMode.Open);
            XmlReader  trainReader = XmlReader.Create(xmlStream);

            //parse the trains from the xml

            while (trainReader.ReadToFollowing("Tren"))
            {
                Train currentTrain = new Train();

                trainReader.MoveToAttribute("CategorieTren");
                currentTrain.Category = trainReader.Value;

                trainReader.MoveToAttribute("KmCum");
                currentTrain.CumulatedKm = (int)float.Parse(trainReader.Value);

                trainReader.MoveToAttribute("Numar");
                currentTrain.OfficialNumber = trainReader.Value;

                trainReader.MoveToAttribute("Lungime");
                currentTrain.Length = int.Parse(trainReader.Value);

                trainReader.MoveToAttribute("Operator");
                currentTrain.OperatorCode = int.Parse(trainReader.Value);

                trainReader.MoveToAttribute("Proprietar");
                currentTrain.OwnerCode = int.Parse(trainReader.Value);

                trainReader.MoveToAttribute("Rang");
                currentTrain.Rank = int.Parse(trainReader.Value);

                trainReader.MoveToAttribute("Tonaj");
                currentTrain.Weight = int.Parse(trainReader.Value);


                //call to TrainRepo goes here to add the train
            }


            //parse all the stations from the routes
            xmlStream.Close();
            xmlStream = new FileStream("trains.xml", FileMode.Open);
            XmlReader stationReader           = XmlReader.Create(xmlStream);
            Dictionary <int, string> stations = new Dictionary <int, string>();

            while (stationReader.ReadToFollowing("ElementTrasa"))
            {
                stationReader.MoveToAttribute("CodStaOrigine");
                int id = int.Parse(stationReader.Value);

                stationReader.MoveToAttribute("DenStaOrigine");
                string stationName = stationReader.Value;

                if (!stations.ContainsKey(id))
                {
                    stations.Add(id, stationName);
                }
            }
            foreach (var station in stations)
            {
                Station currentStation = new Station
                {
                    Name         = station.Value,
                    OfficialCode = station.Key
                };

                //call to station repo to add current station
            }

            //parse all the routes
            xmlStream.Close();
            xmlStream = new FileStream("trains.xml", FileMode.Open);
            XmlReader routeReader = XmlReader.Create(xmlStream);

            while (routeReader.ReadToFollowing("Trasa"))
            {
                Route currentRoute = new Route();

                routeReader.MoveToAttribute("CodStatieFinala");
                currentRoute.DestinationStationCode = int.Parse(routeReader.Value);

                routeReader.MoveToAttribute("CodStatieInitiala");
                currentRoute.OriginStationCode = int.Parse(routeReader.Value);

                routeReader.MoveToAttribute("Tip");
                currentRoute.Type = routeReader.Value;

                routeReader.MoveToContent();
                routeReader.ReadToDescendant("ElementTrasa");
                do
                {
                    RouteNode currentRouteNode = new RouteNode();

                    routeReader.MoveToAttribute("CodStaDest");
                    currentRouteNode.DestinationStationCode = int.Parse(routeReader.Value);

                    routeReader.MoveToAttribute("CodStaOrigine");
                    currentRouteNode.OriginStationCode = int.Parse(routeReader.Value);

                    routeReader.MoveToAttribute("DenStaDestinatie");
                    currentRouteNode.DestinationStationName = routeReader.Value;

                    routeReader.MoveToAttribute("DenStaOrigine");
                    currentRouteNode.OriginStationName = routeReader.Value;

                    routeReader.MoveToAttribute("Km");
                    currentRouteNode.Km = int.Parse(routeReader.Value);

                    /*
                     * Parse Data
                     */

                    routeReader.MoveToAttribute("StationareSecunde");
                    currentRouteNode.Standing = int.Parse(routeReader.Value);

                    // add routenode through repo? YES, we'll do

                    currentRoute.RouteNodes.Add(currentRouteNode);
                } while (routeReader.ReadToNextSibling("ElementTrasa"));

                // add route through route repo
            }
        }
Example #49
0
 public static NetworkTrainPlayer Create(Train train, NetworkPlayer networkPlayer)
 {
     return(new NetworkTrainPlayer(train, networkPlayer));
 }
Example #50
0
        /// <summary>
        /// Getting the count vagons on train.
        /// </summary>
        /// <param name="id">Train id</param>
        /// <returns>The list of vagons.</returns>
        private List <Vagon> GetVagons(int id)
        {
            Train train = repository.Trains.Find(t => t.Vagons, t => t.Id == id).FirstOrDefault();

            return((List <Vagon>)train.Vagons);
        }
Example #51
0
        /// <summary>This method is called once the route and train data have been preprocessed, in order to physically setup the simulation</summary>
        private void SetupSimulation()
        {
            if (Loading.Cancel)
            {
                Close();
            }

            lock (BaseRenderer.GdiPlusLock)
            {
                Timetable.CreateTimetable();
            }
            //Check if any critical errors have occured during the route or train loading
            for (int i = 0; i < Interface.MessageCount; i++)
            {
                if (Interface.LogMessages[i].Type == MessageType.Critical)
                {
                    MessageBox.Show("A critical error has occured:\n\n" + Interface.LogMessages[i].Text + "\n\nPlease inspect the error log file for further information.", "Load", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    Close();
                }
            }
            Program.Renderer.Lighting.Initialize();
            Game.LogRouteName = System.IO.Path.GetFileName(MainLoop.currentResult.RouteFile);
            Game.LogTrainName = System.IO.Path.GetFileName(MainLoop.currentResult.TrainFolder);
            Game.LogDateTime  = DateTime.Now;

            if (Interface.CurrentOptions.LoadInAdvance)
            {
                Textures.LoadAllTextures();
            }
            else
            {
                Program.Renderer.TextureManager.UnloadAllTextures();
            }
            // camera
            Program.Renderer.InitializeVisibility();
            TrainManager.PlayerTrain.DriverBody = new DriverBody(TrainManager.PlayerTrain);
            Program.Renderer.CameraTrackFollower.UpdateAbsolute(0.0, true, false);
            Program.Renderer.CameraTrackFollower.UpdateAbsolute(-0.1, true, false);
            Program.Renderer.CameraTrackFollower.UpdateAbsolute(0.1, true, false);
            Program.Renderer.CameraTrackFollower.TriggerType = EventTriggerType.Camera;
            // starting time and track position
            Program.CurrentRoute.SecondsSinceMidnight = 0.0;
            Game.StartupTime = 0.0;
            int    PlayerFirstStationIndex = -1;
            double PlayerFirstStationPosition;
            int    os = -1;
            bool   f  = false;

            for (int i = 0; i < Program.CurrentRoute.Stations.Length; i++)
            {
                if (!String.IsNullOrEmpty(Game.InitialStationName))
                {
                    if (Game.InitialStationName.ToLowerInvariant() == Program.CurrentRoute.Stations[i].Name.ToLowerInvariant())
                    {
                        PlayerFirstStationIndex = i;
                    }
                }
                if (Program.CurrentRoute.Stations[i].StopMode == StationStopMode.AllStop | Program.CurrentRoute.Stations[i].StopMode == StationStopMode.PlayerStop & Program.CurrentRoute.Stations[i].Stops.Length != 0)
                {
                    if (f == false)
                    {
                        os = i;
                        f  = true;
                    }
                }
            }
            if (PlayerFirstStationIndex == -1)
            {
                if (os == -1)
                {
                    PlayerFirstStationIndex = 0;
                }
                else
                {
                    PlayerFirstStationIndex = os;
                }
            }
            {
                int s = Program.CurrentRoute.Stations[PlayerFirstStationIndex].GetStopIndex(TrainManager.PlayerTrain.NumberOfCars);
                if (s >= 0)
                {
                    PlayerFirstStationPosition = Program.CurrentRoute.Stations[PlayerFirstStationIndex].Stops[s].TrackPosition;

                    double TrainLength = 0.0;
                    for (int c = 0; c < TrainManager.PlayerTrain.Cars.Length; c++)
                    {
                        TrainLength += TrainManager.PlayerTrain.Cars[c].Length;
                    }

                    for (int j = 0; j < Program.CurrentRoute.BufferTrackPositions.Length; j++)
                    {
                        if (PlayerFirstStationPosition > Program.CurrentRoute.BufferTrackPositions[j] && PlayerFirstStationPosition - TrainLength < Program.CurrentRoute.BufferTrackPositions[j])
                        {
                            /*
                             * HACK: The initial start position for the player train is stuck on a set of buffers
                             * This means we have to make some one the fly adjustments to the first station stop position
                             */

                            //Set the start position to be the buffer position plus the train length plus 1m
                            PlayerFirstStationPosition = Program.CurrentRoute.BufferTrackPositions[j] + TrainLength + 1;
                            //Update the station stop location
                            if (s >= 0)
                            {
                                Program.CurrentRoute.Stations[PlayerFirstStationIndex].Stops[s].TrackPosition = PlayerFirstStationPosition;
                            }
                            else
                            {
                                Program.CurrentRoute.Stations[PlayerFirstStationIndex].DefaultTrackPosition = PlayerFirstStationPosition;
                            }
                            break;
                        }
                    }
                }
                else
                {
                    PlayerFirstStationPosition = Program.CurrentRoute.Stations[PlayerFirstStationIndex].DefaultTrackPosition;
                }
                if (Game.InitialStationTime != -1)
                {
                    Program.CurrentRoute.SecondsSinceMidnight = Game.InitialStationTime;
                    Game.StartupTime = Game.InitialStationTime;
                }
                else
                {
                    if (Program.CurrentRoute.Stations[PlayerFirstStationIndex].ArrivalTime < 0.0)
                    {
                        if (Program.CurrentRoute.Stations[PlayerFirstStationIndex].DepartureTime < 0.0)
                        {
                            Program.CurrentRoute.SecondsSinceMidnight = 0.0;
                            Game.StartupTime = 0.0;
                        }
                        else
                        {
                            Program.CurrentRoute.SecondsSinceMidnight = Program.CurrentRoute.Stations[PlayerFirstStationIndex].DepartureTime -
                                                                        Program.CurrentRoute.Stations[PlayerFirstStationIndex].StopTime;
                            Game.StartupTime = Program.CurrentRoute.Stations[PlayerFirstStationIndex].DepartureTime -
                                               Program.CurrentRoute.Stations[PlayerFirstStationIndex].StopTime;
                        }
                    }
                    else
                    {
                        Program.CurrentRoute.SecondsSinceMidnight = Program.CurrentRoute.Stations[PlayerFirstStationIndex].ArrivalTime;
                        Game.StartupTime = Program.CurrentRoute.Stations[PlayerFirstStationIndex].ArrivalTime;
                    }
                }
            }
            int    OtherFirstStationIndex    = -1;
            double OtherFirstStationPosition = 0.0;
            double OtherFirstStationTime     = 0.0;

            for (int i = 0; i < Program.CurrentRoute.Stations.Length; i++)
            {
                if (Program.CurrentRoute.Stations[i].StopMode == StationStopMode.AllStop | Program.CurrentRoute.Stations[i].StopMode == StationStopMode.PlayerPass & Program.CurrentRoute.Stations[i].Stops.Length != 0)
                {
                    OtherFirstStationIndex = i;
                    int s = Program.CurrentRoute.Stations[i].GetStopIndex(TrainManager.PlayerTrain.Cars.Length);
                    if (s >= 0)
                    {
                        OtherFirstStationPosition = Program.CurrentRoute.Stations[i].Stops[s].TrackPosition;
                    }
                    else
                    {
                        OtherFirstStationPosition = Program.CurrentRoute.Stations[i].DefaultTrackPosition;
                    }
                    if (Program.CurrentRoute.Stations[i].ArrivalTime < 0.0)
                    {
                        if (Program.CurrentRoute.Stations[i].DepartureTime < 0.0)
                        {
                            OtherFirstStationTime = 0.0;
                        }
                        else
                        {
                            OtherFirstStationTime = Program.CurrentRoute.Stations[i].DepartureTime - Program.CurrentRoute.Stations[i].StopTime;
                        }
                    }
                    else
                    {
                        OtherFirstStationTime = Program.CurrentRoute.Stations[i].ArrivalTime;
                    }
                    break;
                }
            }
            if (Game.PrecedingTrainTimeDeltas.Length != 0)
            {
                OtherFirstStationTime -= Game.PrecedingTrainTimeDeltas[Game.PrecedingTrainTimeDeltas.Length - 1];
                if (OtherFirstStationTime < Program.CurrentRoute.SecondsSinceMidnight)
                {
                    Program.CurrentRoute.SecondsSinceMidnight = OtherFirstStationTime;
                }
            }
            // initialize trains
            for (int i = 0; i < TrainManager.Trains.Length; i++)
            {
                TrainManager.Trains[i].Initialize();
                int s = TrainManager.Trains[i].IsPlayerTrain ? PlayerFirstStationIndex : OtherFirstStationIndex;
                if (s >= 0)
                {
                    if (Program.CurrentRoute.Stations[s].OpenLeftDoors)
                    {
                        for (int j = 0; j < TrainManager.Trains[i].Cars.Length; j++)
                        {
                            TrainManager.Trains[i].Cars[j].Doors[0].AnticipatedOpen = true;
                        }
                    }
                    if (Program.CurrentRoute.Stations[s].OpenRightDoors)
                    {
                        for (int j = 0; j < TrainManager.Trains[i].Cars.Length; j++)
                        {
                            TrainManager.Trains[i].Cars[j].Doors[1].AnticipatedOpen = true;
                        }
                    }
                }
                if (Program.CurrentRoute.Sections.Length != 0)
                {
                    Program.CurrentRoute.Sections[0].Enter(TrainManager.Trains[i]);
                }
                for (int j = 0; j < TrainManager.Trains[i].Cars.Length; j++)
                {
                    double length = TrainManager.Trains[i].Cars[0].Length;
                    TrainManager.Trains[i].Cars[j].Move(-length);
                    TrainManager.Trains[i].Cars[j].Move(length);
                }
            }

            foreach (var Train in TrainManager.TFOs)
            {
                Train.Initialize();

                foreach (var Car in Train.Cars)
                {
                    double length = Train.Cars[0].Length;
                    Car.Move(-length);
                    Car.Move(length);
                }
            }

            // score
            Game.CurrentScore.ArrivalStation   = PlayerFirstStationIndex + 1;
            Game.CurrentScore.DepartureStation = PlayerFirstStationIndex;
            Game.CurrentScore.Maximum          = 0;
            for (int i = 0; i < Program.CurrentRoute.Stations.Length; i++)
            {
                if (i != PlayerFirstStationIndex & Program.CurrentRoute.Stations[i].PlayerStops())
                {
                    if (i == 0 || Program.CurrentRoute.Stations[i - 1].Type != StationType.ChangeEnds && Program.CurrentRoute.Stations[i - 1].Type != StationType.Jump)
                    {
                        Game.CurrentScore.Maximum += Game.ScoreValueStationArrival;
                    }
                }
            }
            if (Game.CurrentScore.Maximum <= 0)
            {
                Game.CurrentScore.Maximum = Game.ScoreValueStationArrival;
            }
            // signals
            if (Program.CurrentRoute.Sections.Length > 0)
            {
                Program.CurrentRoute.UpdateAllSections();
            }
            // move train in position
            for (int i = 0; i < TrainManager.Trains.Length; i++)
            {
                double p;
                if (TrainManager.Trains[i].IsPlayerTrain)
                {
                    p = PlayerFirstStationPosition;
                }
                else if (TrainManager.Trains[i].State == TrainState.Bogus)
                {
                    p = Program.CurrentRoute.BogusPreTrainInstructions[0].TrackPosition;
                    TrainManager.Trains[i].AI = new Game.BogusPretrainAI(TrainManager.Trains[i]);
                }
                else
                {
                    p = OtherFirstStationPosition;
                }
                for (int j = 0; j < TrainManager.Trains[i].Cars.Length; j++)
                {
                    TrainManager.Trains[i].Cars[j].Move(p);
                }
            }
            // timetable
            if (Timetable.DefaultTimetableDescription.Length == 0)
            {
                Timetable.DefaultTimetableDescription = Game.LogTrainName;
            }

            // initialize camera
            if (Program.Renderer.Camera.CurrentRestriction == CameraRestrictionMode.NotAvailable || Program.Renderer.Camera.CurrentRestriction == CameraRestrictionMode.Restricted3D)
            {
                Program.Renderer.Camera.CurrentMode = CameraViewMode.InteriorLookAhead;
            }
            //Place the initial camera in the driver car
            TrainManager.PlayerTrain.Cars[TrainManager.PlayerTrain.DriverCar].UpdateCamera();
            Program.Renderer.CameraTrackFollower.UpdateAbsolute(-1.0, true, false);
            Program.Renderer.UpdateVisibility(Program.Renderer.CameraTrackFollower.TrackPosition + Program.Renderer.Camera.Alignment.Position.Z);
            Program.Renderer.Camera.SavedExterior = new CameraAlignment(new OpenBveApi.Math.Vector3(-2.5, 1.5, -15.0), 0.3, -0.2, 0.0, PlayerFirstStationPosition, 1.0);
            Program.Renderer.Camera.SavedTrack    = new CameraAlignment(new OpenBveApi.Math.Vector3(-3.0, 2.5, 0.0), 0.3, 0.0, 0.0, TrainManager.PlayerTrain.Cars[0].TrackPosition - 10.0, 1.0);
            // signalling sections
            for (int i = 0; i < TrainManager.Trains.Length; i++)
            {
                int s = TrainManager.Trains[i].CurrentSectionIndex;
                Program.CurrentRoute.Sections[s].Enter(TrainManager.Trains[i]);
            }
            if (Program.CurrentRoute.Sections.Length > 0)
            {
                Program.CurrentRoute.UpdateAllSections();
            }
            // fast-forward until start time
            {
                Game.MinimalisticSimulation = true;
                const double w = 0.25;
                double       u = Game.StartupTime - Program.CurrentRoute.SecondsSinceMidnight;
                if (u > 0)
                {
                    while (true)
                    {
                        double v = u < w ? u : w; u -= v;
                        Program.CurrentRoute.SecondsSinceMidnight += v;
                        TrainManager.UpdateTrains(v);
                        if (u <= 0.0)
                        {
                            break;
                        }
                        TotalTimeElapsedForSectionUpdate += v;
                        if (TotalTimeElapsedForSectionUpdate >= 1.0)
                        {
                            if (Program.CurrentRoute.Sections.Length > 0)
                            {
                                Program.CurrentRoute.UpdateAllSections();
                            }
                            TotalTimeElapsedForSectionUpdate = 0.0;
                        }
                    }
                }
                Game.MinimalisticSimulation = false;
            }
            // animated objects
            ObjectManager.UpdateAnimatedWorldObjects(0.0, true);
            TrainManager.UpdateTrainObjects(0.0, true);
            //HACK: This function calls a single update on all objects attached to the player's train
            //      but ignores any specified damping so that all needles etc. are in the correct place
            //      for the first frame, rather than spinning wildly to get to the starting point.
            TrainManager.PlayerTrain.UpdateCabObjects();
            // timetable
            if (TrainManager.PlayerTrain.Station >= 0)
            {
                Timetable.UpdateCustomTimetable(Program.CurrentRoute.Stations[TrainManager.PlayerTrain.Station].TimetableDaytimeTexture, Program.CurrentRoute.Stations[TrainManager.PlayerTrain.Station].TimetableNighttimeTexture);
                if (Timetable.CustomObjectsUsed != 0 & Timetable.CustomTimetableAvailable && Interface.CurrentOptions.TimeTableStyle != Interface.TimeTableMode.AutoGenerated && Interface.CurrentOptions.TimeTableStyle != Interface.TimeTableMode.None)
                {
                    Timetable.CurrentTimetable = Timetable.TimetableState.Custom;
                }
            }
            //Create AI driver for the player train if specified via the commmand line
            if (Game.InitialAIDriver == true)
            {
                TrainManager.PlayerTrain.AI = new Game.SimpleHumanDriverAI(TrainManager.PlayerTrain, Double.PositiveInfinity);
                if (TrainManager.PlayerTrain.Plugin != null && !TrainManager.PlayerTrain.Plugin.SupportsAI)
                {
                    MessageManager.AddMessage(Translations.GetInterfaceString("notification_aiunable"), MessageDependency.None, GameMode.Expert,
                                              OpenBveApi.Colors.MessageColor.White, Program.CurrentRoute.SecondsSinceMidnight + 10.0, null);
                }
            }

            // warnings / errors
            if (Interface.MessageCount != 0)
            {
                int filesNotFound = 0;
                int errors        = 0;
                int warnings      = 0;
                for (int i = 0; i < Interface.MessageCount; i++)
                {
                    if (Interface.LogMessages[i].FileNotFound)
                    {
                        filesNotFound++;
                    }
                    else if (Interface.LogMessages[i].Type == MessageType.Error)
                    {
                        errors++;
                    }
                    else if (Interface.LogMessages[i].Type == MessageType.Warning)
                    {
                        warnings++;
                    }
                }
                string NotFound = null;
                string Messages;
                if (filesNotFound != 0)
                {
                    NotFound = filesNotFound.ToString() + " file(s) not found";
                    MessageManager.AddMessage(NotFound, MessageDependency.None, GameMode.Expert, MessageColor.Magenta, Program.CurrentRoute.SecondsSinceMidnight + 10.0, null);
                }
                if (errors != 0 & warnings != 0)
                {
                    Messages = errors.ToString() + " error(s), " + warnings.ToString() + " warning(s)";
                    MessageManager.AddMessage(Messages, MessageDependency.None, GameMode.Expert, MessageColor.Magenta, Program.CurrentRoute.SecondsSinceMidnight + 10.0, null);
                }
                else if (errors != 0)
                {
                    Messages = errors.ToString() + " error(s)";
                    MessageManager.AddMessage(Messages, MessageDependency.None, GameMode.Expert, MessageColor.Magenta, Program.CurrentRoute.SecondsSinceMidnight + 10.0, null);
                }
                else
                {
                    Messages = warnings.ToString() + " warning(s)";
                    MessageManager.AddMessage(Messages, MessageDependency.None, GameMode.Expert, MessageColor.Magenta, Program.CurrentRoute.SecondsSinceMidnight + 10.0, null);
                }
                Game.RouteInformation.FilesNotFound     = NotFound;
                Game.RouteInformation.ErrorsAndWarnings = Messages;
                //Print the plugin error encountered (If any) for 10s
                //This must be done after the simulation has init, as otherwise the timeout doesn't work
                if (Loading.PluginError != null)
                {
                    MessageManager.AddMessage(Loading.PluginError, MessageDependency.None, GameMode.Expert, OpenBveApi.Colors.MessageColor.Red, Program.CurrentRoute.SecondsSinceMidnight + 5.0, null);
                    MessageManager.AddMessage(Translations.GetInterfaceString("errors_plugin_failure2"), MessageDependency.None, GameMode.Expert, OpenBveApi.Colors.MessageColor.Red, Program.CurrentRoute.SecondsSinceMidnight + 5.0, null);
                }
            }
            loadComplete          = true;
            RenderRealTimeElapsed = 0.0;
            RenderTimeElapsed     = 0.0;
            World.InitializeCameraRestriction();
            Loading.SimulationSetup = true;
            switch (Game.InitialViewpoint)
            {
            case 0:
                if (Game.InitialReversedConsist)
                {
                    /*
                     * HACK: The cab view has been created using the position of the initial driver car.
                     * Trigger a forced change to ensure that it is now correctly positioned in the consist
                     */
                    TrainManager.PlayerTrain.Cars[TrainManager.PlayerTrain.DriverCar].ChangeCarSection(CarSectionType.Interior);
                }
                break;

            case 1:
                //Switch camera to exterior
                MainLoop.SaveCameraSettings();
                Program.Renderer.Camera.CurrentMode = CameraViewMode.Exterior;
                MainLoop.RestoreCameraSettings();
                for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++)
                {
                    TrainManager.PlayerTrain.Cars[j].ChangeCarSection(CarSectionType.Exterior);
                    //Make bogies visible
                    TrainManager.PlayerTrain.Cars[j].FrontBogie.ChangeSection(0);
                    TrainManager.PlayerTrain.Cars[j].RearBogie.ChangeSection(0);
                    TrainManager.PlayerTrain.Cars[j].Coupler.ChangeSection(0);
                }
                Program.Renderer.Camera.AlignmentDirection = new CameraAlignment();
                Program.Renderer.Camera.AlignmentSpeed     = new CameraAlignment();
                Program.Renderer.UpdateViewport(ViewportChangeMode.NoChange);
                World.UpdateAbsoluteCamera(0.0);
                Program.Renderer.UpdateViewingDistances(Program.CurrentRoute.CurrentBackground.BackgroundImageDistance);
                break;

            case 2:
                //Switch camera to track
                MainLoop.SaveCameraSettings();
                Program.Renderer.Camera.CurrentMode = CameraViewMode.Track;
                MainLoop.RestoreCameraSettings();
                for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++)
                {
                    TrainManager.PlayerTrain.Cars[j].ChangeCarSection(CarSectionType.Exterior);
                    TrainManager.PlayerTrain.Cars[j].FrontBogie.ChangeSection(0);
                    TrainManager.PlayerTrain.Cars[j].RearBogie.ChangeSection(0);
                    TrainManager.PlayerTrain.Cars[j].Coupler.ChangeSection(0);
                }

                Program.Renderer.Camera.AlignmentDirection = new CameraAlignment();
                Program.Renderer.Camera.AlignmentSpeed     = new CameraAlignment();
                Program.Renderer.UpdateViewport(ViewportChangeMode.NoChange);
                World.UpdateAbsoluteCamera(0.0);
                Program.Renderer.UpdateViewingDistances(Program.CurrentRoute.CurrentBackground.BackgroundImageDistance);
                break;

            case 3:
                //Switch camera to flyby
                MainLoop.SaveCameraSettings();
                Program.Renderer.Camera.CurrentMode = CameraViewMode.FlyBy;
                MainLoop.RestoreCameraSettings();
                for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++)
                {
                    TrainManager.PlayerTrain.Cars[j].ChangeCarSection(CarSectionType.Exterior);
                    TrainManager.PlayerTrain.Cars[j].FrontBogie.ChangeSection(0);
                    TrainManager.PlayerTrain.Cars[j].RearBogie.ChangeSection(0);
                    TrainManager.PlayerTrain.Cars[j].Coupler.ChangeSection(0);
                }

                Program.Renderer.Camera.AlignmentDirection = new CameraAlignment();
                Program.Renderer.Camera.AlignmentSpeed     = new CameraAlignment();
                Program.Renderer.UpdateViewport(ViewportChangeMode.NoChange);
                World.UpdateAbsoluteCamera(0.0);
                Program.Renderer.UpdateViewingDistances(Program.CurrentRoute.CurrentBackground.BackgroundImageDistance);
                break;

            case 4:
                //Switch camera to flyby
                MainLoop.SaveCameraSettings();
                Program.Renderer.Camera.CurrentMode = CameraViewMode.FlyByZooming;
                MainLoop.RestoreCameraSettings();
                for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++)
                {
                    TrainManager.PlayerTrain.Cars[j].ChangeCarSection(CarSectionType.Exterior);
                    TrainManager.PlayerTrain.Cars[j].FrontBogie.ChangeSection(0);
                    TrainManager.PlayerTrain.Cars[j].RearBogie.ChangeSection(0);
                    TrainManager.PlayerTrain.Cars[j].Coupler.ChangeSection(0);
                }

                Program.Renderer.Camera.AlignmentDirection = new CameraAlignment();
                Program.Renderer.Camera.AlignmentSpeed     = new CameraAlignment();
                Program.Renderer.UpdateViewport(ViewportChangeMode.NoChange);
                World.UpdateAbsoluteCamera(0.0);
                Program.Renderer.UpdateViewingDistances(Program.CurrentRoute.CurrentBackground.BackgroundImageDistance);
                break;
            }
        }
        internal static Area LoadTestdorfESTW()
        {
            var Area           = new Area("myTestArea", "Testland");
            var EstwTestdorf   = new ESTW("TTST", "Testdorf", "leibit_TEST.dat", Area);
            var EstwRechtsheim = new ESTW("TREH", "Rechtsheim", "leibit_RECHTSHEI.dat", Area);

            var Linksdorf      = new Station("Linksdorf", "TLDF", 30, null, null, EstwTestdorf);
            var LinksdorfTrack = new Track(null, false, false, Linksdorf, null);

            new Block("30BN", eBlockDirection.Right, LinksdorfTrack);
            new Block("31B4711", eBlockDirection.Right, LinksdorfTrack);

            var Probe       = new Station("Probe", "TPRB", 31, "g31_____.abf", "BF31____.abf", EstwTestdorf);
            var ProbeTrack1 = new Track("1", true, true, Probe, null);

            new Block("31G1", eBlockDirection.Both, ProbeTrack1);
            var ProbeTrack2 = new Track("2", true, true, Probe, null);

            new Block("31G2", eBlockDirection.Both, ProbeTrack2);
            var ProbeTrack3 = new Track("3", true, true, Probe, null);

            new Block("31G3", eBlockDirection.Both, ProbeTrack3);

            var UeStMitte      = new Station("ÜSt Mitte", "T UM", 32, null, null, EstwTestdorf);
            var UeStMitteTrack = new Track(null, false, false, UeStMitte, null);

            new Block("32B815", eBlockDirection.Right, UeStMitteTrack);
            new Block("32B816", eBlockDirection.Left, UeStMitteTrack);
            new Block("32B817", eBlockDirection.Right, UeStMitteTrack);
            new Block("31B814", eBlockDirection.Left, UeStMitteTrack);

            var Testdorf        = new Station("Testdorf", "TTST", 32, "g32_____.abf", null, EstwTestdorf);
            var TestdorfTrack1  = new Track("1", true, true, Testdorf, null);
            var TestdorfTrack1A = new Track("1A", true, true, Testdorf, TestdorfTrack1);

            new Block("32G11", eBlockDirection.Both, TestdorfTrack1A);
            var TestdorfTrack1B = new Track("1B", true, true, Testdorf, TestdorfTrack1);

            new Block("32G12", eBlockDirection.Both, TestdorfTrack1B);
            var TestdorfTrack2 = new Track("2", true, true, Testdorf, null);

            new Block("32G21", eBlockDirection.Both, TestdorfTrack2);
            new Block("32G22", eBlockDirection.Both, TestdorfTrack2);
            var TestdorfTrack3 = new Track("3", true, true, Testdorf, null);

            new Block("32G31", eBlockDirection.Both, TestdorfTrack3);
            new Block("32G32", eBlockDirection.Both, TestdorfTrack3);
            var TestdorfTrack4 = new Track("4", true, true, Testdorf, null);

            new Block("32G41", eBlockDirection.Both, TestdorfTrack4);
            var TestdorfTrack4A = new Track("4A", true, true, Testdorf, null);

            new Block("32G42", eBlockDirection.Both, TestdorfTrack4A);

            TestdorfTrack1.Alternatives.Add(TestdorfTrack2);
            TestdorfTrack1.Alternatives.Add(TestdorfTrack3);
            TestdorfTrack1.Alternatives.Add(TestdorfTrack4);
            TestdorfTrack4A.Alternatives.Add(TestdorfTrack1A);
            TestdorfTrack4A.Alternatives.Add(TestdorfTrack2);
            TestdorfTrack4A.Alternatives.Add(TestdorfTrack3);

            var Rechtsheim      = new Station("Rechtsheim", "TREH", 33, null, null, EstwTestdorf);
            var RechtsheimTrack = new Track(null, false, false, Rechtsheim, null);

            new Block("33BP", eBlockDirection.Left, RechtsheimTrack);
            new Block("32B4712", eBlockDirection.Left, RechtsheimTrack);

            var Train2007 = new Train(2007, "IC", "Linksdorf Hbf", "Rechtsheim");

            Area.Trains.TryAdd(2007, Train2007);
            new Schedule(Train2007, null, new LeibitTime(13, 1), ProbeTrack2, _ALL_DAYS, eScheduleDirection.LeftToRight, eHandling.Transit, String.Empty, null);
            new Schedule(Train2007, new LeibitTime(13, 6), new LeibitTime(13, 8), TestdorfTrack1, _ALL_DAYS, eScheduleDirection.LeftToRight, eHandling.StopPassengerTrain, String.Empty, null);

            var Train86312 = new Train(86312, "GC", "Irgendwo", "Linksdorf Gbf");

            Area.Trains.TryAdd(86312, Train86312);
            new Schedule(Train86312, null, new LeibitTime(13, 12), ProbeTrack1, new List <eDaysOfService> {
                eDaysOfService.Tuesday, eDaysOfService.Thursday, eDaysOfService.Friday
            }, eScheduleDirection.RightToLeft, eHandling.Transit, String.Empty, null);
            new Schedule(Train86312, null, new LeibitTime(13, 8), TestdorfTrack3, new List <eDaysOfService> {
                eDaysOfService.Tuesday, eDaysOfService.Thursday, eDaysOfService.Friday
            }, eScheduleDirection.RightToLeft, eHandling.Transit, "Ü 12345", null);

            var Train12345 = new Train(12345, "RB", "Rechtsheim", "Probe");

            Area.Trains.TryAdd(12345, Train12345);
            new Schedule(Train12345, new LeibitTime(13, 6), new LeibitTime(13, 10), TestdorfTrack4, new List <eDaysOfService> {
                eDaysOfService.Monday, eDaysOfService.Tuesday, eDaysOfService.Wednesday, eDaysOfService.Thursday, eDaysOfService.Friday
            }, eScheduleDirection.RightToLeft, eHandling.StopPassengerTrain, "@ 86312", null);

            var ProbeSchedule12345 = new Schedule(Train12345, new LeibitTime(13, 15), null, ProbeTrack3, new List <eDaysOfService> {
                eDaysOfService.Monday, eDaysOfService.Tuesday, eDaysOfService.Wednesday, eDaysOfService.Thursday, eDaysOfService.Friday
            }, eScheduleDirection.RightToLeft, eHandling.Destination, "> 12346", null);

            ProbeSchedule12345.LocalOrders = String.Format("12345 RE     tgl   --> Bahnsteigwende für RB 12346", Environment.NewLine);

            var Train12346 = new Train(12346, "RB", "Probe", "Rechtsheim");

            Area.Trains.TryAdd(12346, Train12346);
            new Schedule(Train12346, null, new LeibitTime(13, 20), ProbeTrack3, new List <eDaysOfService> {
                eDaysOfService.Monday, eDaysOfService.Tuesday, eDaysOfService.Wednesday, eDaysOfService.Thursday, eDaysOfService.Friday
            }, eScheduleDirection.LeftToRight, eHandling.Start, "< 12345", null);
            new Schedule(Train12346, new LeibitTime(13, 18), new LeibitTime(13, 20), ProbeTrack3, new List <eDaysOfService> {
                eDaysOfService.Sunday
            }, eScheduleDirection.LeftToRight, eHandling.StopPassengerTrain, string.Empty, null);
            new Schedule(Train12346, new LeibitTime(13, 25), new LeibitTime(13, 26), TestdorfTrack1B, new List <eDaysOfService> {
                eDaysOfService.Monday, eDaysOfService.Tuesday, eDaysOfService.Wednesday, eDaysOfService.Thursday, eDaysOfService.Friday, eDaysOfService.Sunday
            }, eScheduleDirection.LeftToRight, eHandling.StopPassengerTrain, String.Empty, null);

            var Train60652 = new Train(60652, "RC", "Testdorf", "Rechtsheim");

            Area.Trains.TryAdd(60652, Train60652);
            new Schedule(Train60652, null, new LeibitTime(13, 15), TestdorfTrack4A, new List <eDaysOfService> {
                eDaysOfService.Wednesday
            }, eScheduleDirection.RightToLeft, eHandling.Start, String.Empty, null);
            new Schedule(Train60652, null, new LeibitTime(13, 41), TestdorfTrack2, new List <eDaysOfService> {
                eDaysOfService.Wednesday
            }, eScheduleDirection.LeftToRight, eHandling.Transit, String.Empty, null);

            var ProbeSchedule60652 = new Schedule(Train60652, new LeibitTime(13, 21), new LeibitTime(13, 35), ProbeTrack2, new List <eDaysOfService> {
                eDaysOfService.Wednesday
            }, eScheduleDirection.RightToRight, eHandling.StopFreightTrain, "s. öAno", null);

            ProbeSchedule60652.LocalOrders = String.Format("60652 RC     Mo-Fr  --> 3 Wg (80 m) für RB 14300 Mo-Fr (Ü am Bstg),{0}                        Tfz von Schl Zug zum Bw (über Gl. 12){0}             Sa     --> 3 Wg (80 m) für RB 14302 Sa (bleiben stehen),{0}                        Tfz von Schl Zug zum Bw (über Gl. 12){0}             So     --> 3 Wg (80 m) für RB 14306 So (bleiben stehen),{0}                        Tfz von Schl Zug zum Bw (über Gl. 12)", Environment.NewLine);

            var Train66789 = new Train(66789, "IRC", "Linksdorf Gbf", "Irgendwo");

            Area.Trains.TryAdd(66789, Train66789);
            new Schedule(Train66789, null, new LeibitTime(13, 45), ProbeTrack2, new List <eDaysOfService> {
                eDaysOfService.Tuesday, eDaysOfService.Wednesday, eDaysOfService.Thursday, eDaysOfService.Saturday
            }, eScheduleDirection.LeftToRight, eHandling.Transit, String.Empty, null);
            new Schedule(Train66789, new LeibitTime(13, 50), new LeibitTime(15, 0), TestdorfTrack1, new List <eDaysOfService> {
                eDaysOfService.Tuesday, eDaysOfService.Wednesday, eDaysOfService.Thursday, eDaysOfService.Saturday
            }, eScheduleDirection.LeftToRight, eHandling.StopPassengerTrain, "Ankunft 13:50 Uhr", null);

            var Train65123 = new Train(65123, "KC", "Irgendwo", "Linksdorf Gbf");

            Area.Trains.TryAdd(65123, Train65123);
            new Schedule(Train65123, null, new LeibitTime(0, 12), TestdorfTrack4, new List <eDaysOfService> {
                eDaysOfService.Friday, eDaysOfService.Saturday
            }, eScheduleDirection.RightToLeft, eHandling.Start, String.Empty, null);
            new Schedule(Train65123, new LeibitTime(23, 41), new LeibitTime(0, 12), TestdorfTrack4, new List <eDaysOfService> {
                eDaysOfService.Monday, eDaysOfService.Tuesday, eDaysOfService.Wednesday, eDaysOfService.Thursday
            }, eScheduleDirection.RightToLeft, eHandling.StopPassengerTrain, "Ankunft 23:41 Uhr", null);
            new Schedule(Train65123, null, new LeibitTime(0, 12), ProbeTrack1, new List <eDaysOfService> {
                eDaysOfService.Monday, eDaysOfService.Tuesday, eDaysOfService.Wednesday, eDaysOfService.Thursday
            }, eScheduleDirection.RightToLeft, eHandling.Transit, String.Empty, null);
            new Schedule(Train65123, null, new LeibitTime(0, 12), ProbeTrack1, new List <eDaysOfService> {
                eDaysOfService.Friday, eDaysOfService.Saturday
            }, eScheduleDirection.RightToLeft, eHandling.Transit, String.Empty, null);

            var Train4711 = new Train(4711, "EC", "Linksdorf Hbf", "Nirwana");

            Area.Trains.TryAdd(4711, Train4711);
            new Schedule(Train4711, null, new LeibitTime(14, 5), ProbeTrack2, _ALL_DAYS, eScheduleDirection.LeftToRight, eHandling.Transit, String.Empty, null);

            EstwTestdorf.IsLoaded = true;
            return(Area);
        }
Example #53
0
 internal CylinderCocks(Train train)
 {
     this.Train = train;
 }
Example #54
0
    private void TicketOrderPost()
    {
        string session = Common.utils.NewRequest("session", Common.utils.RequestType.Form);
        //车次关键字
        string key = Common.utils.NewRequest("key", Common.utils.RequestType.Form);
        //上页查询信息
        string date      = HttpUtility.UrlEncode(Common.utils.NewRequest("date", Common.utils.RequestType.Form));
        string startcity = HttpUtility.UrlEncode(Common.utils.NewRequest("startcity", Common.utils.RequestType.Form));
        string endcity   = HttpUtility.UrlEncode(Common.utils.NewRequest("endcity", Common.utils.RequestType.Form));
        string no        = HttpUtility.UrlEncode(Common.utils.NewRequest("no", Common.utils.RequestType.Form));
        string rtyp      = HttpUtility.UrlEncode(Common.utils.NewRequest("rtyp", Common.utils.RequestType.Form));
        string ttype     = HttpUtility.UrlEncode(Common.utils.NewRequest("ttype", Common.utils.RequestType.Form));
        string student   = HttpUtility.UrlEncode(Common.utils.NewRequest("student", Common.utils.RequestType.Form));
        string timearea  = HttpUtility.UrlEncode(Common.utils.NewRequest("timearea", Common.utils.RequestType.Form));

        string outStr = string.Empty;

        string str1 = new Regex(@"JSESSIONID=([^;]*);", RegexOptions.IgnoreCase).Match(session).Groups[1].ToString();
        string str2 = new Regex(@"BIGipServerotsweb=([^;]*);", RegexOptions.IgnoreCase).Match(session).Groups[1].ToString();
        string str  = str1 + "|" + str2;

        Train  send   = new Train();
        string result = send.SendOrderRequest(str, key, date, startcity, endcity, no, rtyp, ttype, student, timearea);

        string userList   = string.Empty;
        string ticketList = string.Empty;
        string priceList  = string.Empty;
        string token      = string.Empty;
        string ticketStr  = string.Empty;
        string train_no   = string.Empty;

        string[] ary = key.Split('#');

        //<input type="hidden" name="org.apache.struts.taglib.html.TOKEN" value="ee3f5476cc070983f99484be47ddd53d">
        //<input type="hidden" name="leftTicketStr" id="left_ticket" value="O013500000M0230000009043000012" />

        if (result.IndexOf("目前您还有未处理的订单") != -1)
        {
            Response.Write("目前您还有未处理的订单,请您到【未完成订单】进行处理");
            Response.End();
            return;
        }

        try
        {
            //返回车票价格阶梯
            userList = Regex.Match(result, @"passengerJson[\s]*=[\s]*([^;]*);").Groups[1].ToString();
            userList = "{\"data\":" + userList + "}";

            //返回联系人列表
            ticketList = Regex.Match(result, @"limitBuySeatTicketDTO[\s]*=[\s]*([^;]*);").Groups[1].ToString();

            //车票价格和剩余数量
            Match match = Regex.Match(result, @"class=""bluetext"">[^<]*</td>[\s]*</tr>[\s]*<tr>[\s]*<td>([^<]*)</td>[\s]*<td>([^<]*)</td>[\s]*<td>([^<]*)</td>");
            priceList = match.Groups[1].ToString() + "," + match.Groups[2].ToString() + "," + match.Groups[3].ToString();

            //token
            token = Regex.Match(result, @"TOKEN""[\s]*value=""([^""]*)""").Groups[1].ToString();

            //ticketstr
            ticketStr = Regex.Match(result, @"left_ticket""[\s]*value=""([^""]*)""").Groups[1].ToString();

            train_no = Regex.Match(result, @"train_no""[\s]*value=""([^""]*)""").Groups[1].ToString();
        }
        catch { }

        //返回验证码
        outStr = ary[0] + "(" + ary[7] + "-" + ary[8] + ")|" + date + " " + ary[2] + "-" + ary[6] + "(" + ary[1] + ")|" + ticketList + "|" + userList + "|" + priceList + "|" + token + "|" + ticketStr + "|" + train_no;

        File.WriteAllText(Server.MapPath("1112.txt"), outStr + "-" + result);

        Log(outStr);

        Response.Write(outStr);
        Response.End();
    }
 // adds a domino picture to a train
 public void ComputerPlayOnTrain(Domino d, Train train, List <PictureBox> trainPBs, int pbIndex)
 {
 }
 // plays a domino on a train.  Loads the appropriate train pb,
 // removes the domino pb from the hand, updates the train status label ,
 // disables the hand pbs and disables appropriate buttons
 public void UserPlayOnTrain(Domino d, Train train, List <PictureBox> trainPBs)
 {
 }
        private static Form GuiTestFramework(int test)
        {
            ////////////////////////////////////////////////////////////////////////////////////////
            //                              Initializations                                       //
            ////////////////////////////////////////////////////////////////////////////////////////


            // Environment object
            var environment = new SimulationEnvironment.SimulationEnvironment();

            IBlock b0 = new TrackModel.Block(1, StateEnum.Healthy, 0, 0, 0, new[] { 0, 0 }, 10, DirEnum.East, new[] { "" }, 0, 0, 0, "Red", 70);
            IBlock b1 = new TrackModel.Block(2, StateEnum.Healthy, 1, 0, 0, new[] { 1, 1 }, 10, DirEnum.East, new[] { "" }, 0, 0, 0, "Red", 70);
            IBlock b2 = new TrackModel.Block(3, StateEnum.Healthy, 2, 0, 0, new[] { 2, 2 }, 10, DirEnum.East, new[] { "" }, 0, 0, 0, "Red", 70);
            IBlock b3 = new TrackModel.Block(4, StateEnum.BrokenTrackFailure, 3, 0, 0, new[] { 3, 3 }, 10, DirEnum.East, new[] { "" }, 0, 0, 0, "Red", 70);

            var sectionA = new List <IBlock> {
                b0
            };
            var sectionB = new List <IBlock> {
                b1, b2
            };
            var sectionC = new List <IBlock> {
                b3
            };

            // Previous track controller's circuit
            var prevCircuit = new TrackCircuit(environment, sectionA);
            // Our track circuit
            var currCircuit = new TrackCircuit(environment, sectionB);
            // Next track controller's circuit
            var nextCircuit = new TrackCircuit(environment, sectionC);

            var prev = new TrackController.TrackController(environment, prevCircuit);
            var curr = new TrackController.TrackController(environment, currCircuit);
            var next = new TrackController.TrackController(environment, nextCircuit);

            //Create TrackModel
            var trackMod = new TrackModel.TrackModel(environment);
            //Let TrackModel read in the lines before you proceed..shouldnt be done this way, but needed to stop CTC Office from faulting
            bool res = trackMod.provideInputFile("red.csv");

            //Console.WriteLine("Res was "+res);
            res = trackMod.provideInputFile("green.csv");
            //Console.WriteLine("Res was " + res);


            environment.TrackModel = trackMod;
            prev.Previous          = null;
            prev.Next = curr;

            curr.Previous = prev;
            curr.Next     = next;

            next.Previous = curr;
            next.Next     = null;

            // Assign the same track controller to both lines
            var office = new CTCOffice.CTCOffice(environment, prev, prev);

            environment.CTCOffice = office;
            environment.PrimaryTrackControllerGreen = prev;
            environment.PrimaryTrackControllerRed   = prev;


            ////////////////////////////////////////////////////////////////////////////////////////
            //                            End Initializations                                     //
            ////////////////////////////////////////////////////////////////////////////////////////

            var form    = new Form();
            var control = new UserControl();

            switch (test)
            {
            case 0:     // SystemScheduler

                var testSystemScheduler = new SystemScheduler.SystemScheduler(environment, office);
                control = new SystemSchedulerGUI(environment, testSystemScheduler, office);
                environment.StartTick();
                break;

            case 1:     // CTCOffice
                environment = null;

                b0 = null;
                b1 = null;
                b2 = null;
                b3 = null;

                sectionA = null;
                sectionB = null;
                sectionC = null;

                prevCircuit = null;
                currCircuit = null;
                nextCircuit = null;

                prev = null;
                curr = null;
                next = null;

                trackMod = null;
                office   = null;

                new CTCGUITest();
                break;

            case 2:     // TrackModel
                control = new TrackModelGUI(environment, trackMod);
                break;

            case 3:     // TrackController
                ITrainModel t = new Train(0, b0, environment);

                environment.AllTrains.Add(t);

                prevCircuit.Trains.Add(0, t);

                control = new TrackControllerUi(environment, environment.PrimaryTrackControllerRed);
                break;

            case 4:     // TrainModel
                var loc = new int[2];
                loc[0] = 10;
                loc[1] = 10;
                var start = new Block(0, StateEnum.Healthy, 0, 0, -0.02, loc, 100, DirEnum.East, null, 1, 2, 0, "Red", 70);
                environment.AddTrain(new Train(0, start, environment));
                environment.AddTrain(new Train(1, start, environment));

                var train0 = (Train)environment.AllTrains[0];
                train0.ChangeMovement(200);

                control = new TrainGUI(environment);

                break;

            case 5:     // TrainController
                var loc2 = new int[2];
                loc2[0] = 10;
                loc2[1] = 10;
                var start2 = new Block(0, StateEnum.Healthy, 0, 0, 0, loc2, 100, DirEnum.East, null, 1, 2, 0, "Red", 70);
                var tc     = new TrainController.TrainController(environment, new Train(0, start2, environment));
                control = new TrainControllerUI(tc, environment);
                break;
            }

            if (environment != null)
            {
                environment.StartTick();
            }

            if (form != null)
            {
                form.Controls.Add(control);
                form.AutoSize = true;
            }
            else
            {
                return(null);
            }


            return(form);
        }
        static void Main()
        {
            var inputLine = Console.ReadLine();

            var mainTrain = new Dictionary <string, List <Train> >();

            while (inputLine != "It's Training Men!")
            {
                var input = inputLine
                            .Split(new char[] { ' ', '-', '>', ':', }, StringSplitOptions.RemoveEmptyEntries)
                            .ToList();



                if (input.Count == 3 && !input.Contains("="))
                {
                    var trainName  = input[0];
                    var wagonName  = input[1];
                    var wagonPower = long.Parse(input[2]);


                    Train train = new Train()
                    {
                        WagonName  = wagonName,
                        WagonPower = wagonPower
                    };


                    if (!mainTrain.ContainsKey(trainName))
                    {
                        mainTrain[trainName] = new List <Train>();
                    }

                    mainTrain[trainName].Add(train);
                }

                else if (input.Count == 2 && !input.Contains("="))
                {
                    var trainName  = input[0];
                    var otherTrain = input[1];


                    if (!mainTrain.ContainsKey(trainName))
                    {
                        mainTrain[trainName] = new List <Train>();
                    }


                    mainTrain[trainName].AddRange(mainTrain[otherTrain]);



                    mainTrain.Remove(otherTrain);
                }

                else
                {
                    var trainName  = input[0];
                    var otherTrain = input[2];

                    if (!mainTrain.ContainsKey(trainName))
                    {
                        mainTrain[trainName] = new List <Train>();
                    }


                    mainTrain[trainName].Clear();

                    mainTrain[trainName].AddRange(mainTrain[otherTrain]);
                }

                inputLine = Console.ReadLine();
            }

            var sTrain = mainTrain.OrderByDescending(t => t.Value.Sum(p => p.WagonPower))
                         .ThenBy(t => t.Value.Count);;



            foreach (var train in sTrain)

            {
                Console.WriteLine($"Train: {train.Key}");

                foreach (var wagon in train.Value.OrderByDescending(x => x.WagonPower))
                {
                    Console.WriteLine($"###{wagon.WagonName} - {wagon.WagonPower}");
                }
            }
        }
Example #59
0
    public static DistanceData DataExtraction(SPData SPData, Train train, Follower wagen)
    {
        int    f      = 1;
        Branch branch = SPData.DictBranches[wagen._BranchKey];

        if (train.IsForward)
        {
            f = wagen.Reverse ? 1 : -1;
        }
        else
        {
            f = wagen.Reverse ? -1 : 1;
        }

        wagen.DistanceData.Position = Vector3.zero;
        wagen.DistanceData.Rotation = Quaternion.identity;
        wagen.DistanceData.Index    = 0;

        for (int i = branch.VertexDistance.Count - 2; i >= 0; i--)
        {
            if (wagen.Progress >= branch.VertexDistance[i])
            {
                wagen.DistanceData.Index = i;
                break;
            }
        }

        var a = wagen.DistanceData.Index;
        var b = wagen.DistanceData.Index + 1;

        var vertexA = branch.Vertices[a];
        var vertexB = branch.Vertices[b];

        var tangentA = branch.Tangents[a];
        var tangentB = branch.Tangents[b];


        var normalA = branch.Normals[a];
        var normalB = branch.Normals[b];

        var vertexDistanceA = branch.VertexDistance[a];
        var vertexDistanceB = branch.VertexDistance[b];

        var EdgeProgress = Mathf.InverseLerp(vertexDistanceA, vertexDistanceB, wagen.Progress);

        var pos = Vector3.Lerp(vertexA, vertexB, EdgeProgress);

        wagen.DistanceData.Position = (wagen.Trans) ? pos : (pos + wagen.Position);

        if (SPData.InterpolateRotation)
        {
            Quaternion FirstNodeRot  = (SPData.Is2D) ? Quaternion.LookRotation(normalA, f * tangentA) : Quaternion.LookRotation(f * tangentA, normalA);
            Quaternion SecondNodeRot = (SPData.Is2D) ? Quaternion.LookRotation(normalB, f * tangentB) : Quaternion.LookRotation(f * tangentB, normalB);
            wagen.DistanceData.Rotation = Quaternion.Lerp(FirstNodeRot, SecondNodeRot, EdgeProgress);
        }
        else
        {
            var dir = vertexB - vertexA;
            wagen.DistanceData.Rotation = (SPData.Is2D) ? Quaternion.LookRotation(normalA, f * dir) : Quaternion.LookRotation(f * dir, normalA);
        }
        wagen.DistanceData.Rotation *= Quaternion.Euler(wagen.Rotation);
        return(wagen.DistanceData);
    }
 public TrainTests()
 {
     train = new Train();
     wagon = new Wagon();
 }