예제 #1
0
        public string ExhaustingLocos(MSGExhaust exhaust)
        {
            string tmp = "";

            if (exhaust == null)
            {
                exhaust = new MSGExhaust();
            }
            foreach (OnlineLocomotive l in OnlineLocomotives)
            {
                if (l.userName != MultiPlayerManager.GetUserName())
                {
                    Train t = MultiPlayerManager.FindPlayerTrain(l.userName);
                    if (t != null && l.trainCarPosition < t.Cars.Count && (Math.Abs(t.SpeedMpS) > 0.001 || Math.Abs(t.LastReportedSpeed) > 0))
                    {
                        if (t.Cars[l.trainCarPosition] is MSTSDieselLocomotive)
                        {
                            exhaust.AddNewItem(l.userName, t, l.trainCarPosition);
                        }
                    }
                }
            }
            if (exhaust != null)
            {
                tmp += exhaust.ToString();
            }
            return(tmp);
        }
예제 #2
0
 //check if it is in the server mode && they are players && not allow autoswitch
 public static bool NoAutoSwitch()
 {
     if (!MultiPlayerManager.IsMultiPlayer() || MultiPlayerManager.IsServer())
     {
         return(false);
     }
     //if (MPManager.IsClient()) return true;
     return(!MultiPlayerManager.AllowedManualSwitch); //aloow manual switch or not
 }
예제 #3
0
 public static MultiPlayerManager Instance()
 {
     if (localUser == null)
     {
         Catalog   = CatalogManager.Catalog;
         Random    = new Random();
         localUser = new MultiPlayerManager();
     }
     return(localUser);
 }
예제 #4
0
        public void SwitchPlayerTrain(MSGPlayerTrainSw player)
        {
            // find info about the new player train
            // look in all trains

            if (MultiPlayerManager.Client != null && player.user == MultiPlayerManager.Client.UserName)
            {
                return;                                                                                         //do not add self//WARNING: may need to worry about train number here
            }
            OnlinePlayer p;
            var          doesPlayerExist = Players.TryGetValue(player.user, out p);

            if (!doesPlayerExist)
            {
                return;
            }
            if (player.oldTrainReverseFormation)
            {
                p.Train.ReverseFormation(false);
            }
            p.LeadingLocomotiveID = player.leadingID;
            Train train;

            if (MultiPlayerManager.IsServer()) //server needs to worry about correct train number
            {
                train           = Simulator.Instance.Trains.Find(t => t.Number == player.num);
                train.TrainType = TrainType.Remote;
            }
            else
            {
                train           = Simulator.Instance.Trains.Find(t => t.Number == player.num);
                train.TrainType = TrainType.Remote;
            }
            p.Train = train;
            if (player.newTrainReverseFormation)
            {
                p.Train.ReverseFormation(false);
            }
        }
예제 #5
0
        }                                   //when in true, will not force this player out, to protect the one that others uses the same name

        // Used to restore
        public OnlinePlayer(BinaryReader inf)
        {
            if (null == inf)
            {
                throw new ArgumentNullException(nameof(inf));
            }

            Username            = inf.ReadString();
            LeadingLocomotiveID = inf.ReadString();
            int trainNo = inf.ReadInt32();

            Train          = Simulator.Instance.Trains.GetTrainByNumber(trainNo);
            Consist        = inf.ReadString();
            Path           = inf.ReadString();
            CreatedTime    = inf.ReadDouble();
            AvatarUrl      = inf.ReadString();
            QuitTime       = inf.ReadDouble();
            Status         = (OnlinePlayerStatus)inf.ReadInt32();
            Protected      = inf.ReadBoolean();
            Status         = OnlinePlayerStatus.Quit;
            Train.SpeedMpS = 0;
            QuitTime       = Simulator.Instance.GameTime; // allow a total of 10 minutes to reenter game.
            for (int i = 0; i < Train.Cars.Count; i++)
            {
                TrainCar car = Train.Cars[i];
                if (car is MSTSLocomotive && MultiPlayerManager.IsServer())
                {
                    MultiPlayerManager.Instance().AddOrRemoveLocomotive(Username, Train.Number, i, true);
                }
            }

            if (!MultiPlayerManager.Instance().lostPlayer.ContainsKey(Username))
            {
                MultiPlayerManager.Instance().lostPlayer.Add(Username, this);
                MultiPlayerManager.Instance().AddRemovedPlayer(this);//add this player to be removed
            }
        }
예제 #6
0
        private async Task Connection(IPAddress address, int port)
        {
            byte[] buffer = new byte[8192];
            int    bytesRead;
            string content;

            try
            {
                await client.ConnectAsync(address, port).ConfigureAwait(false);

                NetworkStream networkStream = client.GetStream();

                while (client.Connected && !cts.Token.IsCancellationRequested)
                {
                    bytesRead = await networkStream.ReadAsync(buffer.AsMemory(0, buffer.Length), cts.Token).ConfigureAwait(false);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    decoder.PushMsg(Encoding.Unicode.GetString(buffer, 0, bytesRead));

                    while ((content = decoder.GetMsg()) != null)
                    {
                        try
                        {
                            Message message = Message.Decode(content);
                            if (Connected || message is MSGRequired)
                            {
                                message.HandleMsg();
                            }
                        }
                        catch (Exception ex) when(ex is InvalidDataException)
                        {
                        }
                    }
                }
            }
            catch (Exception ex) when(ex is MultiPlayerException)
            {
            }
            catch (Exception ex) when(ex is SocketException || ex is IOException ||
                                      ex is OperationCanceledException || ex is TaskCanceledException)
            {
            }

            Simulator.Instance.Confirmer?.Error(CatalogManager.Catalog.GetString("Connection to the server is lost, will play as single mode"));
            foreach (System.Collections.Generic.KeyValuePair <string, OnlinePlayer> p in MultiPlayerManager.OnlineTrains.Players)
            {
                MultiPlayerManager.Instance().AddRemovedPlayer(p.Value);
            }

            //no matter what, let player gain back the control of the player train
            if (Simulator.Instance.PlayerLocomotive?.Train != null)
            {
                Simulator.Instance.PlayerLocomotive.Train.TrainType      = TrainType.Player;
                Simulator.Instance.PlayerLocomotive.Train.LeadLocomotive = Simulator.Instance.PlayerLocomotive;
            }
            Simulator.Instance.Confirmer?.Information(CatalogManager.Catalog.GetString("Alt-E to gain control of your train"));

            MultiPlayerManager.Client = null;
            client.Close();
        }
예제 #7
0
        public void AddPlayers(MSGPlayer player)
        {
            if (Players.ContainsKey(player.user))
            {
                return;
            }
            if (MultiPlayerManager.Client != null && player.user == MultiPlayerManager.Client.UserName)
            {
                return; //do not add self//WARNING: may need to worry about train number here
            }
            OnlinePlayer p = new OnlinePlayer(player.user,
                                              Path.Combine(Simulator.Instance.RouteFolder.ContentFolder.ConsistsFolder, player.con),
                                              Path.Combine(Simulator.Instance.RouteFolder.PathsFolder, player.path));

            p.AvatarUrl           = player.url;
            p.LeadingLocomotiveID = player.leadingID;
            Train train = new Train();

            train.TrainType = TrainType.Remote;
            if (MultiPlayerManager.IsServer()) //server needs to worry about correct train number
            {
            }
            else
            {
                train.Number = player.num;
            }
            if (player.con.Contains("tilted"))
            {
                train.IsTilting = true;
            }
            int direction = player.dir;

            train.DistanceTravelled = player.Travelled;
            train.TrainMaxSpeedMpS  = player.trainmaxspeed;

            if (MultiPlayerManager.IsServer())
            {
                try
                {
                    AIPath aiPath = new AIPath(Simulator.Instance.TrackDatabase, Simulator.Instance.TSectionDat, p.Path, Simulator.Instance.TimetableMode);
                }
                catch (Exception) { MultiPlayerManager.BroadCast((new MSGMessage(player.user, "Warning", "Server does not have path file provided, signals may always be red for you.")).ToString()); }
            }

            try
            {
                train.RearTDBTraveller = new Traveller(Simulator.Instance.TSectionDat, Simulator.Instance.TrackDatabase.TrackDB.TrackNodes, player.Location, direction == 1 ? Traveller.TravellerDirection.Forward : Traveller.TravellerDirection.Backward);
            }
            catch (Exception e)
            {
                if (MultiPlayerManager.IsServer())
                {
                    MultiPlayerManager.BroadCast((new MSGMessage(player.user, "Error", "MultiPlayer Error:" + e.Message)).ToString());
                }
                else
                {
                    throw new Exception();
                }
            }
            for (var i = 0; i < player.cars.Length; i++)// cars.Length-1; i >= 0; i--) {
            {
                string   wagonFilePath = Path.Combine(Simulator.Instance.RouteFolder.ContentFolder.TrainSetsFolder, player.cars[i]);
                TrainCar car           = null;
                try
                {
                    car            = RollingStock.Load(Simulator.Instance, wagonFilePath);
                    car.CarLengthM = player.lengths[i] / 100.0f;
                }
                catch (Exception error)
                {
                    Trace.WriteLine(error.Message);
                    car = MultiPlayerManager.Instance().SubCar(wagonFilePath, player.lengths[i]);
                }
                if (car == null)
                {
                    continue;
                }
                bool flip = true;
                if (player.flipped[i] == 0)
                {
                    flip = false;
                }
                car.Flipped = flip;
                car.CarID   = player.ids[i];
                train.Cars.Add(car);
                car.Train = train;
                MSTSWagon w = (MSTSWagon)car;
                if (w != null)
                {
                    w.SignalEvent((player.pantofirst == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 1);
                    w.SignalEvent((player.pantosecond == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 2);
                    w.SignalEvent((player.pantothird == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 3);
                    w.SignalEvent((player.pantofourth == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 4);
                }
            }// for each rail car

            if (train.Cars.Count == 0)
            {
                throw (new Exception("The train of player " + player.user + " is empty from "));
            }

            train.ControlMode = TrainControlMode.Explorer;
            train.CheckFreight();
            train.InitializeBrakes();
            TrackCircuitPartialPathRoute tempRoute = train.CalculateInitialTrainPosition();

            if (tempRoute.Count == 0)
            {
                MultiPlayerManager.BroadCast((new MSGMessage(p.Username, "Error", "Cannot be placed into the game")).ToString());//server will broadcast this error
                throw new InvalidDataException("Remote train original position not clear");
            }

            train.SetInitialTrainRoute(tempRoute);
            train.CalculatePositionOfCars();
            train.ResetInitialTrainRoute(tempRoute);

            train.CalculatePositionOfCars();
            train.AITrainBrakePercent = 100;

            //if (MPManager.Instance().AllowedManualSwitch) train.InitializeSignals(false);
            for (int iCar = 0; iCar < train.Cars.Count; iCar++)
            {
                var car = train.Cars[iCar];
                if (car.CarID == p.LeadingLocomotiveID)
                {
                    train.LeadLocomotive = car;
                    (train.LeadLocomotive as MSTSLocomotive).Headlight    = player.headlight;
                    (train.LeadLocomotive as MSTSLocomotive).UsingRearCab = player.frontorrearcab == "R" ? true : false;
                }
                if (car is MSTSLocomotive && MultiPlayerManager.IsServer())
                {
                    MultiPlayerManager.Instance().AddOrRemoveLocomotive(player.user, train.Number, iCar, true);
                }
            }
            if (train.LeadLocomotive == null)
            {
                train.LeadNextLocomotive();
                if (train.LeadLocomotive != null)
                {
                    p.LeadingLocomotiveID = train.LeadLocomotive.CarID;
                }
                else
                {
                    p.LeadingLocomotiveID = "NA";
                }
            }

            if (train.LeadLocomotive != null)
            {
                train.Name = Train.GetTrainName(train.LeadLocomotive.CarID);
            }
            else if (train.Cars != null && train.Cars.Count > 0)
            {
                train.Name = Train.GetTrainName(train.Cars[0].CarID);
            }
            else if (player != null && player.user != null)
            {
                train.Name = player.user;
            }

            if (MultiPlayerManager.IsServer())
            {
                train.InitializeSignals(false);
            }
            p.Train = train;

            Players.Add(player.user, p);
            MultiPlayerManager.Instance().AddOrRemoveTrain(train, true);
        }