Exemplo n.º 1
0
        public string ExhaustingLocos(MSGExhaust exhaust)
        {
            string tmp = "";

            if (exhaust == null)
            {
                exhaust = new MSGExhaust();
            }
            foreach (OnlineLocomotive l in OnlineLocomotives)
            {
                if (l.userName != MPManager.GetUserName())
                {
                    Train t = MPManager.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);
        }
Exemplo n.º 2
0
        public bool protect  = false;        //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)
        {
            Username            = inf.ReadString();
            LeadingLocomotiveID = inf.ReadString();
            var trainNo = inf.ReadInt32();

            Train          = MPManager.Simulator.Trains.GetTrainByNumber(trainNo);
            con            = inf.ReadString();
            path           = inf.ReadString();
            CreatedTime    = inf.ReadDouble();
            url            = inf.ReadString();
            quitTime       = inf.ReadDouble();
            status         = (Status)inf.ReadInt32();
            protect        = inf.ReadBoolean();
            status         = Status.Quit;
            Train.SpeedMpS = 0;
            quitTime       = MPManager.Simulator.GameTime; // allow a total of 10 minutes to reenter game.
            for (int iCar = 0; iCar < Train.Cars.Count; iCar++)
            {
                var car = Train.Cars[iCar];
                if (car is MSTSLocomotive && MPManager.IsServer())
                {
                    MPManager.Instance().AddOrRemoveLocomotive(Username, Train.Number, iCar, true);
                }
            }
            if (!MPManager.Instance().lostPlayer.ContainsKey(this.Username))
            {
                MPManager.Instance().lostPlayer.Add(Username, this);
                MPManager.Instance().AddRemovedPlayer(this);//add this player to be removed
            }
        }
Exemplo n.º 3
0
 //check if it is in the client mode
 public static bool IsClient()
 {
     if (!MPManager.IsMultiPlayer() || MPManager.IsServer())
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 4
0
 //check if it is in the server mode && they are players && not allow autoswitch
 public static bool NoAutoSwitch()
 {
     if (!MPManager.IsMultiPlayer() || MPManager.IsServer())
     {
         return(false);
     }
     //if (MPManager.IsClient()) return true;
     return(!MPManager.AllowedManualSwitch); //aloow manual switch or not
 }
Exemplo n.º 5
0
 public static MPManager Instance()
 {
     if (localUser == null)
     {
         Catalog   = new GettextResourceManager("Orts.Simulation");
         Random    = new Random();
         localUser = new MPManager();
     }
     return(localUser);
 }
Exemplo n.º 6
0
 public static MPManager Instance()
 {
     if (localUser == null)
     {
         Catalog   = new Catalog("Orts.Simulation", RuntimeInfo.LocalesFolder);
         Random    = new Random();
         localUser = new MPManager();
     }
     return(localUser);
 }
Exemplo n.º 7
0
        public void AddPlayer()
        {
            if (!MPManager.IsServer())
            {
                return;
            }
            if (PlayerAdded == true)
            {
                PlayerAdded = false;
                MPManager.Instance().lastPlayerAddedTime = Simulator.GameTime;
                MPManager.Instance().lastSwitchTime      = Simulator.GameTime;

                MSGPlayer host = new  MSGPlayer(MPManager.GetUserName(), "1234", Simulator.conFileName, Simulator.patFileName, Simulator.PlayerLocomotive.Train,
                                                Simulator.PlayerLocomotive.Train.Number, Simulator.Settings.AvatarURL);
                MPManager.BroadCast(host.ToString() + MPManager.OnlineTrains.AddAllPlayerTrain());
                foreach (Train t in Simulator.Trains)
                {
                    if (Simulator.PlayerLocomotive != null && t == Simulator.PlayerLocomotive.Train)
                    {
                        continue;                                                                              //avoid broadcast player train
                    }
                    if (MPManager.FindPlayerTrain(t))
                    {
                        continue;
                    }
                    if (removedTrains.Contains(t))
                    {
                        continue;                           //this train is going to be removed, should avoid it.
                    }
                    MPManager.BroadCast((new MSGTrain(t, t.Number)).ToString());
                }
                if (CheckSpad == false)
                {
                    MultiPlayer.MPManager.BroadCast((new MultiPlayer.MSGMessage("All", "OverSpeedOK", "OK to go overspeed and pass stop light")).ToString());
                }
                else
                {
                    MultiPlayer.MPManager.BroadCast((new MultiPlayer.MSGMessage("All", "NoOverSpeed", "Penalty for overspeed and passing stop light")).ToString());
                }
                MPManager.BroadCast(GetEnvInfo());
            }
        }
Exemplo n.º 8
0
        public void SwitchPlayerTrain(MSGPlayerTrainSw player)
        {
            // find info about the new player train
            // look in all trains

            if (MPManager.Client != null && player.user == MPManager.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 (MPManager.IsServer()) //server needs to worry about correct train number
            {
                train           = MPManager.Simulator.Trains.Find(t => t.Number == player.num);
                train.TrainType = Train.TRAINTYPE.REMOTE;
            }
            else
            {
                train           = MPManager.Simulator.Trains.Find(t => t.Number == player.num);
                train.TrainType = Train.TRAINTYPE.REMOTE;
            }
            p.Train = train;
            if (player.newTrainReverseFormation)
            {
                p.Train.ReverseFormation(false);
            }
        }
Exemplo n.º 9
0
        public void Receive(object client)
        {
            TcpClient     tcpClient    = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[8192];
            int    bytesRead;

            while (true)
            {
                bytesRead = 0;
                //System.Threading.Thread.Sleep(Program.Random.Next(50, 200));
                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 8192);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }

                //message has successfully been received
                string info = "";
                try
                {
                    decoder.PushMsg(Encoding.Unicode.GetString(message, 0, bytesRead));                    //encoder.GetString(message, 0, bytesRead));
                    info = decoder.GetMsg();
                    while (info != null)
                    {
                        //System.Console.WriteLine(info);
                        Message msg = Message.Decode(info);
                        if (Connected || msg is MSGRequired)
                        {
                            msg.HandleMsg();
                        }
                        info = decoder.GetMsg();
                    }
                }
                catch (MultiPlayerError)
                {
                    break;
                }
                catch (SameNameError)                 //I have conflict with some one in the game, will close, and abort.
                {
                    if (MPManager.Simulator.Confirmer != null)
                    {
                        MPManager.Simulator.Confirmer.Error(MPManager.Catalog.GetString("Connection to the server is lost, will play as single mode"));
                    }
                    MPManager.Client = null;
                    tcpClient.Close();
                    listenThread.Abort();
                }
                catch (Exception e)
                {
                    System.Console.WriteLine(e.Message + e.StackTrace);
                    Trace.TraceWarning(e.Message + e.StackTrace);
                }
            }
            if (MPManager.Simulator.Confirmer != null)
            {
                MPManager.Simulator.Confirmer.Error(MPManager.Catalog.GetString("Connection to the server is lost, will play as single mode"));
            }
            try
            {
                foreach (var p in MPManager.OnlineTrains.Players)
                {
                    MPManager.Instance().AddRemovedPlayer(p.Value);
                }
            }
            catch (Exception) { }

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

            MPManager.Client = null;
            tcpClient.Close();
            listenThread.Abort();
        }
Exemplo n.º 10
0
        public void AddPlayers(MSGPlayer player, OnlinePlayer p)
        {
            if (Players.ContainsKey(player.user))
            {
                return;
            }
            if (MPManager.Client != null && player.user == MPManager.Client.UserName)
            {
                return;                                                                       //do not add self//WARNING: may need to worry about train number here
            }
            if (p == null)
            {
                p = new OnlinePlayer(null, null);
            }
            p.url = player.url;
            p.LeadingLocomotiveID = player.leadingID;
            p.con  = MPManager.Simulator.BasePath + "\\TRAINS\\CONSISTS\\" + player.con;
            p.path = MPManager.Simulator.RoutePath + "\\PATHS\\" + player.path;
            Train train = new Train(MPManager.Simulator);

            train.TrainType = Train.TRAINTYPE.REMOTE;
            if (MPManager.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.travelled        = player.Travelled;
            train.TrainMaxSpeedMpS = player.trainmaxspeed;

            if (MPManager.IsServer())
            {
                try
                {
#if ACTIVITY_EDITOR
                    AIPath aiPath = new AIPath(MPManager.Simulator.TDB, MPManager.Simulator.TSectionDat, p.path, MPManager.Simulator.TimetableMode, MPManager.Simulator.orRouteConfig);
#else
                    AIPath aiPath = new AIPath(MPManager.Simulator.TDB, MPManager.Simulator.TSectionDat, p.path);
#endif
                }
                catch (Exception) { MPManager.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(MPManager.Simulator.TSectionDat, MPManager.Simulator.TDB.TrackDB.TrackNodes, player.TileX, player.TileZ, player.X, player.Z, direction == 1 ? Traveller.TravellerDirection.Forward : Traveller.TravellerDirection.Backward);
            }
            catch (Exception e)
            {
                if (MPManager.IsServer())
                {
                    MPManager.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 = MPManager.Simulator.BasePath + @"\trains\trainset\" + player.cars[i];
                TrainCar car;

                try
                {
                    car            = RollingStock.Load(MPManager.Simulator, train, wagonFilePath);
                    car.CarLengthM = player.lengths[i] / 100.0f;
                }
                catch (Exception error)
                {
                    Console.WriteLine(error.Message);
                    car = MPManager.Instance().SubCar(train, wagonFilePath, player.lengths[i]);
                }

                if (car == null)
                {
                    continue;
                }

                car.Flipped = player.flipped[i] != 0;
                car.CarID   = player.ids[i];

                if (car is MSTSWagon w)
                {
                    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);
                }
            }

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

            p.Username        = player.user;
            train.ControlMode = Train.TRAIN_CONTROL.EXPLORER;
            train.CheckFreight();
            train.InitializeBrakes();
            bool canPlace = true;
            Train.TCSubpathRoute tempRoute = train.CalculateInitialTrainPosition(ref canPlace);
            if (tempRoute.Count == 0 || !canPlace)
            {
                MPManager.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 && MPManager.IsServer())
                {
                    MPManager.Instance().AddOrRemoveLocomotive(player.user, train.Number, iCar, true);
                }
            }
            if (train.LeadLocomotive == null)
            {
                train.LeadNextLocomotive();
                p.LeadingLocomotiveID = train.LeadLocomotive?.CarID ?? "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?.user != null)
            {
                train.Name = player.user;
            }

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

            Players.Add(player.user, p);
            MPManager.Instance().AddOrRemoveTrain(train, true);
        }
Exemplo n.º 11
0
        public void Receive(object client)
        {
            NetworkStream clientStream = Client.GetStream();

            byte[] message = new byte[8192];
            int    bytesRead;
            int    errorCount     = 0;
            double firstErrorTick = 0;
            double nowTicks       = 0;

            while (true)
            {
                //System.Threading.Thread.Sleep(Program.Random.Next(50, 200));

                bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 8192);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }

                //message has successfully been received
                string info = "";
                try
                {
                    decoder.PushMsg(Encoding.Unicode.GetString(message, 0, bytesRead));                    //encoder.GetString(message, 0, bytesRead));
                    info = decoder.GetMsg();
                    while (info != null)
                    {
                        //System.Console.WriteLine(info);
                        Message msg = Message.Decode(info);
                        if (msg is MSGPlayer)
                        {
                            ((MSGPlayer)msg).HandleMsg(this);
                        }
                        else
                        {
                            msg.HandleMsg();
                        }

                        info = decoder.GetMsg();
                    }
                }
                catch (MultiPlayerError)
                {
                    break;
                }
                catch (SameNameError)
                {
                    Client.Close();
                    thread.Abort();
                }
                catch (Exception)
                {
                    nowTicks = MPManager.Simulator.GameTime;
                    if (firstErrorTick == 0)
                    {
                        firstErrorTick = nowTicks;
                        errorCount     = 1;
                    }
                    if (errorCount >= 5 && nowTicks - firstErrorTick < 10)                     //5 errors last 10 seconds
                    {
                        MSGMessage emsg = new MSGMessage(this.Username, "Error", "Too many errors received from you in a short period of time.");
                        MPManager.BroadCast(emsg.ToString());
                        break;
                    }
                    else if (errorCount < 5)
                    {
                        errorCount++;
                    }
                    else
                    {
                        firstErrorTick = nowTicks; errorCount = 0;
                    }
                    //System.Console.WriteLine(e.Message + info);
                }
            }

            System.Console.WriteLine("{0} quit", this.Username);
            if (MPManager.Simulator.Confirmer != null)
            {
                MPManager.Simulator.Confirmer.Information(MPManager.Catalog.GetStringFmt("{0} quit.", this.Username));
            }
            Client.Close();
            if (this.Train != null && this.status != Status.Removed)             //remember the location of the train in case the player comes back later, if he is not removed by the dispatcher
            {
                if (!MPManager.Instance().lostPlayer.ContainsKey(this.Username))
                {
                    MPManager.Instance().lostPlayer.Add(this.Username, this);
                }
                this.quitTime       = MPManager.Simulator.GameTime;
                this.Train.SpeedMpS = 0.0f;
                this.status         = Status.Quit;
            }
            MPManager.Instance().AddRemovedPlayer(this);            //add this player to be removed
            MPManager.BroadCast((new MSGQuit(this.Username)).ToString());
            thread.Abort();
        }