コード例 #1
0
        public void FindLinks(string[] words, FileType type, TasClient tas, TasSayEventArgs e)
        {
            if (words.Length == 0)
            {
                Battle b = tas.MyBattle;
                if (b == null) return;
                ah.Respond(e, string.Format("Getting Zero-K mirrors for currently hosted {0}", type));
                if (type == FileType.Map) GetLinksAsync(b.MapName, e);
                else GetLinksAsync(b.ModName, e);
            }
            else
            {
                int[] resultIndexes;
                string[] resultVals;
                int cnt;
                if (type == FileType.Map) cnt = ah.FilterMaps(words, out resultVals, out resultIndexes);
                else cnt = ah.FilterMods(words, out resultVals, out resultIndexes);

                if (cnt == 0) ah.Respond(e, string.Format("No such {0} found", type));
                else
                {
                    ah.Respond(e, string.Format("Getting Zero-K mirrors for {0}, please wait", resultVals[0]));
                    GetLinksAsync(resultVals[0], e);
                }
            }
        }
コード例 #2
0
        public Nightwatch()
		
        {
            tas = new TasClient("NightWatch");
			config = new Config();
            Trace.Listeners.Add(new NightwatchTraceListener(tas));
        }
コード例 #3
0
        public BrowserInterop(TasClient tas, Config conf) {
            login = conf.LobbyPlayerName;
            password = conf.LobbyPlayerPassword;
            var baseUrl = GlobalConst.BaseSiteUrl;
            WindowsApi.InternetSetCookiePub(baseUrl, GlobalConst.LoginCookieName, login);
            WindowsApi.InternetSetCookiePub(baseUrl, GlobalConst.PasswordHashCookieName, ZkData.Utils.HashLobbyPassword(password));
            WindowsApi.InternetSetCookiePub(baseUrl, GlobalConst.LobbyAccessCookieName, "1");


            tas.LoginAccepted += delegate
                {
                    login = tas.UserName;
                    password = tas.UserPassword;
                    var wc = new WebClient();
                    var uri =
                        new Uri(string.Format("{2}/Home/Logon?login={0}&password={1}",
                                              Uri.EscapeDataString(login),
                                              Uri.EscapeDataString(password), 
                                              GlobalConst.BaseSiteUrl));

                    WindowsApi.InternetSetCookiePub(baseUrl, GlobalConst.LoginCookieName, login);
                    WindowsApi.InternetSetCookiePub(baseUrl, GlobalConst.PasswordHashCookieName, ZkData.Utils.HashLobbyPassword(password));

                    if (conf.IsFirstRun) wc.DownloadString(uri);
                    else wc.DownloadStringAsync(uri);
                };
        }
コード例 #4
0
        public PwBar()
        {
            InitializeComponent();
            tas = Program.TasClient;
            timerLabel.AutoSize = true;
            headerLabel.AutoSize = true;

            timer = new Timer();
            timer.Interval = 1000;
            timer.Tick += (sender, args) =>
            {
                if (Program.NotifySection.Contains(this)) timerLabel.Text = ZkData.Utils.PrintTimeRemaining((int)deadline.Subtract(DateTime.Now).TotalSeconds);
            };
            timer.Start();

            pnl.Controls.Add(timerLabel);
            pnl.Controls.Add(headerLabel);

            // TODO pw handling 
            /*tas.Extensions.JsonDataReceived += (sender, e) =>
            {
                var newPw = e as PwMatchCommand;
                if (newPw != null)
                {
                    pw = newPw;
                    UpdateGui();
                }
            };*/

            tas.MyUserStatusChanged += (sender, args) => UpdateGui();
        }
コード例 #5
0
        public NwSteamHandler(TasClient tas, string webApiKey)
        {
            steamApi = new SteamWebApi(GlobalConst.SteamAppID, webApiKey);
            tas.Said += (sender, args) =>
            {
                if (args.Place == SayPlace.User && args.UserName != tas.UserName && args.Text.StartsWith("!linksteam"))
                {
                    var token = args.Text.Substring(11);
                    User user;
                    if (tas.ExistingUsers.TryGetValue(args.UserName, out user))
                    {

                        Utils.StartAsync(() =>
                        {
                            Thread.Sleep(2000); // steam is slow to get the ticket from client .. wont verify if its checked too soon
                            var steamID = steamApi.WebValidateAuthToken(token);
                            var info = steamApi.WebGetPlayerInfo(steamID);

                            using (var db = new ZkDataContext())
                            {
                                var acc = db.Accounts.Find(user.AccountID);
                                acc.SteamID = steamID;
                                acc.SteamName = info.personaname;
                                db.SubmitAndMergeChanges();
                                tas.Extensions.PublishAccountData(acc);
                            }
                        });
                    }


                }

            };
        }
コード例 #6
0
        public void RunNub(int num)
        {
            var tas = new TasClient("Nubotron");
            var name = "TestNub" + num;
            var ord = num / 16;
            var batname = "Test " + ord;

            //tas.Input += (sender, args) => { Console.WriteLine(" < {0}", args); };
            //tas.Output += (sender, args) => { Console.WriteLine(" > {0}", args); };

            tas.Connected += (sender, args) => {
                tas.Login(name, "dummy");
            };

            tas.ConnectionLost += (sender, args) => { tas.Connect(GlobalConst.LobbyServerHost, GlobalConst.LobbyServerPort); Console.WriteLine("disconnected"); };


            tas.LoginAccepted += (sender, args) => { Console.WriteLine(name + " accepted"); };
            tas.LoginDenied += (sender, args) => { tas.Register(name, "dummy"); };

            tas.RegistrationAccepted += (sender, args) => { tas.Login(name, "dummy"); };
            tas.RegistrationDenied += (sender, response) => { Console.WriteLine(name + "registration denied"); };

            

            tas.UserAdded += (sender, args) => {
                if (args.Name == name) {
                    tas.JoinChannel("bots");
                    if (num%16 == 0) tas.OpenBattle(new BattleHeader()
                    {
                        Title = batname,
                        MaxPlayers = 16,
                    });
                    else {
                        var bat = tas.ExistingBattles.Values.FirstOrDefault(x => x.Title == batname);
                        if (bat != null) tas.JoinBattle(bat.BattleID);
                    }
                }
            };
            tas.BattleFound += (sender, args) => {
                if (args.Title == batname) {
                    //await Task.Delay(200);
                    tas.JoinBattle(args.BattleID);
                }
            };
            

            tas.Connect(GlobalConst.LobbyServerHost, GlobalConst.LobbyServerPort);
            /*Task.Factory.StartNew(async () =>
            {
                while (true)
                {
                    await Task.Delay(rand.Next(400000));
                    tas.Say(SayPlace.Channel, "zk", sent.GetNext(), false);
                }
            }, TaskCreationOptions.LongRunning);*/
        }
コード例 #7
0
        public ConnectBar(TasClient tasClient): this() {
            client = tasClient;

            client.ConnectionLost += (s, e) =>
            {
                {
                    if (!client.WasDisconnectRequested) lbState.Text = "disconnected, reconnecting...";
                    else
                    {
                        lbState.Text = "disconnected";
                        tasClientConnectCalled = false;
                    }
                    Program.NotifySection.AddBar(this);
                }
            };

            client.Connected += (s, e) =>
            {
                lbState.Text = "Connected, logging in ...";
                if (string.IsNullOrEmpty(Program.Conf.LobbyPlayerName) || string.IsNullOrEmpty(Program.Conf.LobbyPlayerPassword)) LoginWithDialog("Please choose your name and password.\nThis will create a new account if it does not exist.");
                else client.Login(Program.Conf.LobbyPlayerName, Program.Conf.LobbyPlayerPassword);
            };

            client.LoginAccepted += (s, e) =>
            {
                Program.NotifySection.RemoveBar(this);
                //Program.MainWindow.navigationControl.Path = "battles";
            };

            client.LoginDenied += (s, e) =>
            {
                if (e.ResultCode == LoginResponse.Code.InvalidName && !string.IsNullOrEmpty(Program.Conf.LobbyPlayerPassword))
                {
                    if (
                        MessageBox.Show(
                            string.Format("Account '{0}' does not exist yet, do you want to create it?", Program.Conf.LobbyPlayerName),
                            "Confirm account registration",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        lbState.Text = "Registering a new account";
                        client.Register(Program.Conf.LobbyPlayerName, Program.Conf.LobbyPlayerPassword);
                    } else LoginWithDialog(string.Format("Login denied: {0} {1}", e.ResultCode.Description(), e.Reason));
                } else
                {
                    LoginWithDialog(
                        string.Format("Login denied: {0} {1}\nChoose a different name to create new account.", e.ResultCode.Description(), e.Reason));
                }
            };

            client.RegistrationDenied +=
                (s, e) => LoginWithDialog(string.Format("Registration denied: {0} {1}", e.ResultCode.Description(), e.Reason));

            client.RegistrationAccepted += (s, e) => client.Login(Program.Conf.LobbyPlayerName, Program.Conf.LobbyPlayerPassword);
        }
コード例 #8
0
 public ServerImagesHandler(SpringPaths springPaths, TasClient tas) {
     basePath = Utils.MakePath(springPaths.WritableDirectory, "LuaUI", "Configs");
     tas.BattleUserJoined += (sender, args) =>
         {
             // preload avatar images on user join battle so that they are available ingame
             User us;
             if (tas.ExistingUsers.TryGetValue(args.UserName, out us)) {
                 GetAvatarImage(us);
                 GetClanOrFactionImage(us);
             }
         };
 }
コード例 #9
0
        public ChatRelay(TasClient zkTas, string password, List<string> channels)
        {
            this.springTas = new LobbyClient.Legacy.TasClient(null, "ChatRelay", 0);
            this.channels = channels;
            this.zkTas = zkTas;
            springTas.LoginAccepted += OnLoginAccepted;
            zkTas.LoginAccepted += OnLoginAccepted;
            springTas.Said += OnSaid;
            zkTas.Said += OnSaid;

            SetupSpringTasConnection(password);
        }
コード例 #10
0
        public ZklSteamHandler(TasClient tas)
        {
            this.tas = tas;
            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
				if (Environment.Is64BitProcess)
				{
					EmbeddedResourceExtractor.ExtractFile ("ZeroKLobby.NativeLibs.libCSteamworks-x86_64.so", "libCSteamworks.so");
					EmbeddedResourceExtractor.ExtractFile ("ZeroKLobby.NativeLibs.libsteam_api-x86_64.so", "libsteam_api.so");
				}
				else
				{
					EmbeddedResourceExtractor.ExtractFile ("ZeroKLobby.NativeLibs.libCSteamworks.so", "libCSteamworks.so");
					EmbeddedResourceExtractor.ExtractFile ("ZeroKLobby.NativeLibs.libsteam_api.so", "libsteam_api.so");
				}
            }
            else
            {
                EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.CSteamworks.dll", "CSteamworks.dll");
                EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.steam_api.dll", "steam_api.dll");
            }
            EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.steam_appid.txt", "steam_appid.txt");

            SteamHelper = new SteamClientHelper();
            SteamHelper.SteamOnline += () =>
            {
                SteamName = SteamHelper.GetMyName();
                friends = SteamHelper.GetFriends();
                SteamID = SteamHelper.GetSteamID();
                if (tas.IsLoggedIn && tas.MyUser != null && tas.MyUser.EffectiveElo != 0) OnLoggedToBothSteamAndTas();
            };


            tas.MyUserStatusChanged += (sender, args) => { if (SteamHelper.IsOnline && SteamID != 0) OnLoggedToBothSteamAndTas(); };
            tas.UserStatusChanged += (sender, args) =>
            {
                if (args?.New?.SteamID != null && args?.Old?.SteamID != args?.New?.SteamID && args?.New?.SteamID !=0) {
                    Voice.AddListenerSteamID(args.New.SteamID.Value); // todo only for battle in future
                    if (friends.Contains(args.New.SteamID.Value)) AddFriend(args.New.Name);
                }
            };

            tas.UserRemoved += (sender, args) =>
            {
                User us;
                if (tas.ExistingUsers.TryGetValue(args.Name, out us) && us.SteamID.HasValue)
                {
                    Voice.RemoveListenerSteamID(us.SteamID.Value);
                }
            };
        }
コード例 #11
0
        public PlanetWarsMatchMaker(TasClient tas)
        {
            AttackOptions = new List<AttackOption>();
            RunningBattles = new Dictionary<string, AttackOption>();

            var db = new ZkDataContext();
            pwHostName = db.AutohostConfigs.First(x => x.AutohostMode == AutohostMode.Planetwars).Login.TrimNumbers();

            Galaxy gal = db.Galaxies.First(x => x.IsDefault);
            factions = db.Factions.Where(x => !x.IsDeleted).ToList();

            MatchMakerState dbState = null;
            if (gal.MatchMakerState != null)
            {
                try
                {
                    dbState = JsonConvert.DeserializeObject<MatchMakerState>(gal.MatchMakerState);
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }
            }
            if (dbState != null)
            {
                AttackerSideCounter = dbState.AttackerSideCounter;
                AttackOptions = dbState.AttackOptions;
                Challenge = dbState.Challenge;
                ChallengeTime = dbState.ChallengeTime;
                AttackerSideChangeTime = dbState.AttackerSideChangeTime;
                RunningBattles = dbState.RunningBattles;
            }
            else
            {
                AttackerSideCounter = gal.AttackerSideCounter;
                AttackerSideChangeTime = gal.AttackerSideChangeTime ?? DateTime.UtcNow;
            }

            this.tas = tas;
            tas.PreviewSaid += TasOnPreviewSaid;
            tas.UserRemoved += TasOnUserRemoved;
            tas.ChannelUserAdded += TasOnChannelUserAdded;
            tas.ChannelJoined += (sender, args) => { if (args.Name == "extension") tas.Extensions.SendJsonData(GenerateLobbyCommand()); };

            timer = new Timer(10000);
            timer.AutoReset = true;
            timer.Elapsed += TimerOnElapsed;
            timer.Start();
        }
コード例 #12
0
        public void RunNub(int num)
        {
            var tas = new TasClient("Nubotron");
            var name = "TestNub" + num;
            var ord = num / 16;
            var batname = "Test " + ord;

            //tas.Input += (sender, args) => { Console.WriteLine(" < {0}", args); };
            //tas.Output += (sender, args) => { Console.WriteLine(" > {0}", args); };

            tas.Connected += (sender, args) => {
                tas.Login(name, "dummy");
            };

            tas.ConnectionLost += (sender, args) => { Console.WriteLine("disconnected"); };


            tas.LoginAccepted += (sender, args) => { Console.WriteLine(name + " accepted"); };
            tas.LoginDenied += (sender, args) => { tas.Register(name, "dummy"); };

            

            tas.UserAdded += (sender, args) => {
                if (args.Name == name) {
                    tas.JoinChannel("bots");
                    if (num%16 == 0) tas.OpenBattle(new BattleHeader()
                    {
                        Engine = "91.0",
                        Game  = "Zero-K v1.3.1.15",
                        Title = "test" + ord,
                        Map = "SmallDivide",
                        MaxPlayers = 16,
                    });
                    else {
                        var bat = tas.ExistingBattles.Values.FirstOrDefault(x => x.Title == batname);
                        if (bat != null) tas.JoinBattle(bat.BattleID);
                    }
                }
            };
            tas.BattleFound += (sender, args) => {
                if (args.Title == batname) {
                    //await Task.Delay(200);
                    tas.JoinBattle(args.BattleID);
                }
            };

            tas.Connect(GlobalConst.LobbyServerHost, GlobalConst.LobbyServerPort);
        }
コード例 #13
0
	    public void Init(TasClient tasClient)
	    {
	        client = tasClient;

	        client.ConnectionLost += (s, e) => {
	            {
	                if (!client.WasDisconnectRequested) lbState.Text = "disconnected, reconnecting...";
	                else {
	                    lbState.Text = "disconnected";
	                    tasClientConnectCalled = false;
	                }
	            }
	        };

	        client.Connected += (s, e) => {
                btnLogout.Text = "Logout";
	            lbState.Text = "Connected, logging in ...";
	            if (string.IsNullOrEmpty(Program.Conf.LobbyPlayerName) || string.IsNullOrEmpty(Program.Conf.LobbyPlayerPassword)) LoginWithDialog("Please choose your name and password.\nThis will create a new account if it does not exist.");
	            else client.Login(Program.Conf.LobbyPlayerName, Program.Conf.LobbyPlayerPassword);
	        };

	        client.LoginAccepted += (s, e) => {
	            lbState.Text = client.UserName;
	            pictureBox1.Image = Program.ServerImages.GetAvatarImage(client.MyUser);
	            playerItem = new PlayerListItem() { UserName = client.UserName };
	        };

	        client.LoginDenied += (s, e) => {
	            if (e.ResultCode == LoginResponse.Code.InvalidName && !string.IsNullOrEmpty(Program.Conf.LobbyPlayerPassword)) {
	                if (
	                    MessageBox.Show(string.Format("Account '{0}' does not exist yet, do you want to create it?", Program.Conf.LobbyPlayerName), "Confirm account registration",
	                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) {
	                    lbState.Text = "Registering a new account";
	                    client.Register(Program.Conf.LobbyPlayerName, Program.Conf.LobbyPlayerPassword);
	                } else {
                        LoginWithDialog(string.Format("Login denied: {0} {1}", e.ResultCode.Description(), e.Reason));
	                }
	            } else {
	                LoginWithDialog(string.Format("Login denied: {0} {1}\nChoose a different name to create new account.", e.ResultCode.Description(), e.Reason));
	            }
	        };

	        client.RegistrationDenied += (s, e) => LoginWithDialog(string.Format("Registration denied: {0} {1}", e.ResultCode.Description(), e.Reason));

	        client.RegistrationAccepted += (s, e) => client.Login(Program.Conf.LobbyPlayerName, Program.Conf.LobbyPlayerPassword);
	    }
コード例 #14
0
		public ConnectBar(TasClient tasClient): this()
		{
			client = tasClient;

			
			client.ConnectionLost += (s, e) =>
				{
					canRegister = false;
					{
						if (!client.WasDisconnectRequested) lbState.Text = "disconnected due to network problem, autoreconnecting...";
						else
						{
							lbState.Text = "disconnected";
							tasClientConnectCalled = false;
						}
						Program.NotifySection.AddBar(this);
					}
				};

			client.Connected += (s, e) =>
				{
					canRegister = false;
					Program.NotifySection.RemoveBar(this);
					lbState.Text = "Connected, logging in ...";
                    if (string.IsNullOrEmpty(Program.Conf.LobbyPlayerName) || string.IsNullOrEmpty(Program.Conf.LobbyPlayerPassword)) LoginWithDialog("Please enter your name and password", true);
					else client.Login(Program.Conf.LobbyPlayerName, Program.Conf.LobbyPlayerPassword);
				};

			client.LoginAccepted += (s, e) => Program.NotifySection.RemoveBar(this);

			client.LoginDenied += (s, e) =>
				{
                    if (e.Data.ResultCode == LoginResponse.Code.InvalidName && !string.IsNullOrEmpty(Program.Conf.LobbyPlayerPassword) && canRegister)
					{
						lbState.Text = "Registering new account";
						client.Register(Program.Conf.LobbyPlayerName, Program.Conf.LobbyPlayerPassword);
					}
					else LoginWithDialog(string.Format("Login denied: {0} {1}",e.Data.ResultCode, e.Data.Reason), false);
				};

			client.RegistrationDenied += (s, e) => LoginWithDialog(string.Format("Registration denied: {0} {1}", e.Data.ResultCode.Description(), e.Data.Reason), true);

            client.RegistrationAccepted += (s, e) => client.Login(Program.Conf.LobbyPlayerName, Program.Conf.LobbyPlayerPassword);

		}
コード例 #15
0
		public OfflineMessages(TasClient client)
		{
			this.client = client;
			client.UserAdded += client_UserAdded;
			client.Said += client_Said;
			client.LoginAccepted += client_LoginAccepted;
			client.ChannelUserAdded += client_ChannelUserAdded;
		    try
		    {
		        using (var db = new ZkDataContext())
		        {
		            db.Database.ExecuteSqlCommand("DELETE FROM LobbyMessages WHERE Created < {0}", DateTime.UtcNow.AddDays(-14));
		        }
		    }
		    catch (Exception ex)
		    {
		        Trace.TraceError(ex.ToString());
		    }
		}
コード例 #16
0
        public CaClient(TcpClient cli, TasClient tas)
        {
            try
            {
                con = new ClientConnection();
                con.ConnectionClosed += con_ConnectionClosed;
                con.CommandRecieved += con_CommandRecieved;

                this.tas = tas;
                tas.BattleUserJoined += tas_BattleUserJoined;
                tas.BattleInfoChanged += tas_BattleInfoChanged;

                con.Connect(cli);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                throw;
            }
        }
コード例 #17
0
        public MatchMakerBar(TasClient client)
        {
            this.client = client;
            InitializeComponent();
            lbText.Font = Config.GeneralFont;
            bitmapButton1.Text = "Stop";

            client.MatchMakerStatusUpdated += (sender, status) =>
            {
                if (!status.MatchMakerEnabled) Program.NotifySection.RemoveBar(this);
                else
                {
                    lbText.Text = "In queue: " + string.Join(", ", status.JoinedQueues.Select(x=>$"{x} ({status.QueueCounts[x]} people)"));
                    Program.NotifySection.AddBar(this);
                }
            };

            client.Connected += (sender, welcome) =>
                { Program.NotifySection?.RemoveBar(this); };

            client.ConnectionLost += (sender, welcome) =>
            { Program.NotifySection?.RemoveBar(this); };

        }
コード例 #18
0
        public void Dispose()
        {
            try
            {
                if (tas != null)
                {
                    tas.BattleUserJoined -= tas_BattleUserJoined;
                    tas.BattleInfoChanged -= tas_BattleInfoChanged;
                    tas = null;
                }

                if (con != null)
                {
                    con.ConnectionClosed -= con_ConnectionClosed;
                    con.CommandRecieved -= con_CommandRecieved;
                    con.Dispose();
                    con = null;
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
        }
コード例 #19
0
        public static void Main(string[] args)
        {
            try
            {
                //Stopwatch stopWatch = new Stopwatch(); stopWatch.Start();

                Trace.Listeners.Add(new ConsoleTraceListener());
                Trace.Listeners.Add(new LogTraceListener());

                if (Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    var ver = GetNetVersionFromRegistry();
                    if (ver < 378675)
                    {
                        MessageBox.Show("Zero-K launcher needs Microsoft .NET framework 4.5.1\nPlease download and install it first",
                                        "Program is unable to run", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }


                Directory.SetCurrentDirectory(StartupPath);

                SelfUpdater = new SelfUpdater("Zero-K");

                // if (Process.GetProcesses().Any(x => x.ProcessName.StartsWith("spring_"))) return; // dont start if started from installer
                StartupArgs = args;


                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!Debugger.IsAttached)
                {
                    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                    Thread.GetDomain().UnhandledException += UnhandledException;
                    Application.ThreadException += Application_ThreadException;
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                }

                //HttpWebRequest.DefaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);



                Trace.TraceInformation("Starting with version {0}", SelfUpdater.CurrentVersion);

                WebRequest.DefaultWebProxy = null;
                ThreadPool.SetMaxThreads(500, 2000);
                ServicePointManager.Expect100Continue = false;
                if (Environment.OSVersion.Platform != PlatformID.Unix && !Conf.UseExternalBrowser)
                {
                    Utils.SetIeCompatibility();
                }                                                                                                                  //set to current IE version

                LoadConfig();


                var contentDir = !string.IsNullOrEmpty(Conf.DataFolder) ? Conf.DataFolder : StartupPath;
                if (!Directory.Exists(contentDir) || !SpringPaths.IsDirectoryWritable(contentDir) || pickInitFolder)
                {
                    var dc = new SelectWritableFolder()
                    {
                        SelectedPath = SpringPaths.GetMySpringDocPath()
                    };
                    if (dc.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    contentDir = dc.SelectedPath;
                }
                if (Conf.DataFolder != StartupPath)
                {
                    Conf.DataFolder = contentDir;
                }
                else
                {
                    Conf.DataFolder = null;
                }

                if (!SpringPaths.IsDirectoryWritable(StartupPath) || StartupPath.Contains("Local\\Apps"))
                {
                    MessageBox.Show(
                        string.Format(
                            "Please use the newly created desktop icon to start Zero-K not this one.\r\nZero-K.exe will be moved to {0}",
                            contentDir), "Startup directory is not writable!");
                    var newTarget = Path.Combine(contentDir, "Zero-K.exe");
                    if (SelfUpdater.CheckForUpdate(newTarget, true))
                    {
                        Conf.Save(Path.Combine(contentDir, Config.ConfigFileName));
                        Process.Start(newTarget);
                        return;
                    }
                    MessageBox.Show("Move failed, please copy Zero-K.exe to a writable folder");
                }



                if (Conf.IsFirstRun)
                {
                    Utils.CreateDesktopShortcut();
                    if (Environment.OSVersion.Platform != PlatformID.Unix)
                    {
                        Utils.RegisterProtocol();
                    }
                }

                SpringPaths = new SpringPaths(null, writableFolderOverride: contentDir);
                SpringPaths.MakeFolders();
                SpringPaths.SetEnginePath(Utils.MakePath(SpringPaths.WritableDirectory, "engine", ZkData.GlobalConst.DefaultEngineOverride ?? TasClient.ServerSpringVersion));

                // run unitsync as soon as possible so we don't have to spend several minutes doing it on game start
                // two problems:
                // 1) unitsync can only be loaded once, even if in a different directory http://msdn.microsoft.com/en-us/library/ms682586.aspx#factors_that_affect_searching
                //  so if we do it in SpringVersionChanged it'll be done at startup for GlobalConst.DefaultEngineOverride, then for no other engine version
                // 2) unitsync can't be unloaded http://stackoverflow.com/questions/1371877/how-to-unload-the-dll-using-c
                // also see EngineDownload.cs
                //SpringPaths.SpringVersionChanged += (s, e) =>
                //{
                //    //System.Diagnostics.Trace.TraceInformation("SpringPaths version: {0}", SpringPaths.SpringVersion);
                //    //new PlasmaShared.UnitSyncLib.UnitSync(SpringPaths);
                //    //SpringScanner.VerifyUnitSync();
                //    //if (SpringScanner != null) SpringScanner.Dispose();
                //    //SpringScanner = new SpringScanner(SpringPaths);
                //    //SpringScanner.Start();
                //};

                SaveConfig();


                try
                {
                    if (!Debugger.IsAttached)
                    {
                        var wp = "";
                        foreach (var c in SpringPaths.WritableDirectory.Where(x => (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z')))
                        {
                            wp += c;
                        }
                        mutex = new Mutex(false, "ZeroKLobby" + wp);
                        if (!mutex.WaitOne(10000, false))
                        {
                            MessageBox.Show(
                                "Another copy of Zero-K lobby is still running" +
                                "\nMake sure the other lobby is closed (check task manager) before starting new one",
                                "There can be only one lobby running",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Stop);
                            return;
                        }
                    }
                }
                catch (AbandonedMutexException) { }

                FriendManager      = new FriendManager();
                AutoJoinManager    = new AutoJoinManager();
                EngineConfigurator = new EngineConfigurator(SpringPaths.WritableDirectory);

                SpringScanner = new SpringScanner(SpringPaths);
                SpringScanner.LocalResourceAdded   += (s, e) => Trace.TraceInformation("New resource found: {0}", e.Item.InternalName);
                SpringScanner.LocalResourceRemoved += (s, e) => Trace.TraceInformation("Resource removed: {0}", e.Item.InternalName);
                if (Program.Conf.EnableUnitSyncPrompt && Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    SpringScanner.UploadUnitsyncData += MicroForms.UnitSyncUploadPrompt.SpringScanner_UploadUnitsyncData;
                    SpringScanner.RetryResourceCheck += MicroForms.UnitSyncRetryPrompt.SpringScanner_RetryGetResourceInfo;
                }

                SpringScanner.MapRegistered += (s, e) => Trace.TraceInformation("Map registered: {0}", e.MapName);
                SpringScanner.ModRegistered += (s, e) => Trace.TraceInformation("Mod registered: {0}", e.Data.Name);

                Downloader = new PlasmaDownloader.PlasmaDownloader(Conf, SpringScanner, SpringPaths); //rapid
                Downloader.DownloadAdded += (s, e) => Trace.TraceInformation("Download started: {0}", e.Data.Name);

                var isLinux = Environment.OSVersion.Platform == PlatformID.Unix;
                TasClient = new TasClient(string.Format("ZK {0}{1}", SelfUpdater.CurrentVersion, isLinux ? " linux" : ""));

                SayCommandHandler = new SayCommandHandler(TasClient);

                ServerImages = new ServerImagesHandler(SpringPaths, TasClient);


                // log, for debugging
                TasClient.Connected     += (s, e) => Trace.TraceInformation("TASC connected");
                TasClient.LoginAccepted += (s, e) =>
                {
                    Trace.TraceInformation("TASC login accepted");
                    Trace.TraceInformation("Server is using Spring version {0}", TasClient.ServerSpringVersion);
                    if (Environment.OSVersion.Platform == PlatformID.Unix || Conf.UseExternalBrowser)
                    {
                        MainWindow.navigationControl.Path = "battles";
                    }
                };

                TasClient.LoginDenied    += (s, e) => Trace.TraceInformation("TASC login denied");
                TasClient.ChannelJoined  += (s, e) => { Trace.TraceInformation("TASC channel joined: " + e.Name); };
                TasClient.ConnectionLost += (s, e) => Trace.TraceInformation("Connection lost");

                // special handling
                TasClient.PreviewSaid += (s, e) =>
                {
                    var  tas  = (TasClient)s;
                    User user = null;
                    if (e.Data.UserName != null)
                    {
                        tas.ExistingUsers.TryGetValue(e.Data.UserName, out user);
                        if ((user != null && user.BanMute) || Conf.IgnoredUsers.Contains(e.Data.UserName))
                        {
                            e.Cancel = true;
                        }
                    }
                };

                TasClient.Extensions.JsonDataReceived += (eventArgs, o) =>
                {
                    var command = o as ProtocolExtension.SiteToLobbyCommand;
                    if (command != null)
                    {
                        MainWindow.navigationControl.Path = command.SpringLink;
                        MainWindow.PopupSelf();
                    }
                };

                ConnectBar        = new ConnectBar(TasClient);
                ModStore          = new ModStore();
                ToolTip           = new ToolTipHandler();
                BrowserInterop    = new BrowserInterop(TasClient, Conf);
                BattleIconManager = new BattleIconManager();

                Application.AddMessageFilter(ToolTip);


                SteamHandler = new ZklSteamHandler(TasClient);
                SteamHandler.Connect();


                MainWindow = new MainWindow();

                Application.AddMessageFilter(new ScrollMessageFilter());


                if (Conf.StartMinimized)
                {
                    MainWindow.WindowState = FormWindowState.Minimized;
                }
                else
                {
                    MainWindow.WindowState = FormWindowState.Normal;
                }
                MainWindow.Size = new Size(Math.Min(SystemInformation.VirtualScreen.Width - 30, MainWindow.Width),
                                           Math.Min(SystemInformation.VirtualScreen.Height - 30, MainWindow.Height));  //in case user have less space than 1024x768

                BattleBar     = new BattleBar();
                NewVersionBar = new NewVersionBar(SelfUpdater);
                VoteBar       = new VoteBar();
                PwBar         = new PwBar();

                //This make the size of every bar constant (only for height).
                //We wanted to make them constant because the bar get DPI-scaled twice/thrice/multiple-time (especially for reusable bar).
                //Setting maximum height upon creation will hopefully make sure it is not DPI-scaled multiple time.
                var votebarSize = new Size(0, VoteBar.Height);
                // Reference: http://stackoverflow.com/questions/5314041/set-minimum-window-size-in-c-sharp-net
                var newversionbarSize = new Size(0, NewVersionBar.Height);
                var battlebarSize     = new Size(0, BattleBar.Height);
                var connectbarSize    = new Size(0, ConnectBar.Height);

                VoteBar.MinimumSize       = votebarSize; //fix minimum size forever
                VoteBar.MaximumSize       = votebarSize; //fix maximum size forever
                NewVersionBar.MinimumSize = newversionbarSize;
                NewVersionBar.MaximumSize = newversionbarSize;
                BattleBar.MinimumSize     = battlebarSize;
                BattleBar.MaximumSize     = battlebarSize;
                ConnectBar.MinimumSize    = connectbarSize;
                ConnectBar.MaximumSize    = connectbarSize;
                //End battlebar size hax

                if (!Debugger.IsAttached && !Conf.DisableAutoUpdate)
                {
                    Program.SelfUpdater.StartChecking();
                }

                //if (Conf.IsFirstRun) Utils.OpenWeb(GlobalConst.BaseSiteUrl + "/Wiki/LobbyStart", false);

                // download primary engine & game
                MainWindow.Paint += GetSpringZK;
                Downloader.PackageDownloader.MasterManifestDownloaded += GetSpringZK;


                // Format and display the TimeSpan value.
                //stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
                //Trace.TraceInformation("1 Runtime {0}", elapsedTime);



                Application.Run(MainWindow);
                ShutDown();
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleException(ex, true);
            }
            finally
            {
                ShutDown();
            }
            if (ErrorHandling.HasFatalException && !Program.CloseOnNext)
            {
                Application.Restart();
            }
        }
コード例 #20
0
 public VoteForceStart(TasClient tas, Spring spring, AutoHost ah): base(tas, spring, ah) {}
コード例 #21
0
 public VoteForceStart(TasClient tas, Spring spring, AutoHost ah) : base(tas, spring, ah)
 {
 }
コード例 #22
0
        public static void Main(string[] args)
        {
            try
            {
                //Stopwatch stopWatch = new Stopwatch(); stopWatch.Start();

                Trace.Listeners.Add(new ConsoleTraceListener());
                Trace.Listeners.Add(new LogTraceListener());

                /*
                if (Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    var ver = GetNetVersionFromRegistry();
                    if (ver < 378675)
                    {
                        MessageBox.Show("Zero-K launcher needs Microsoft .NET framework 4.5.1\nPlease download and install it first",
                            "Program is unable to run", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                */

                Directory.SetCurrentDirectory(StartupPath);

                SelfUpdater = new SelfUpdater("Zero-K_NET4.0");

                // if (Process.GetProcesses().Any(x => x.ProcessName.StartsWith("spring_"))) return; // dont start if started from installer
                StartupArgs = args;


                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!Debugger.IsAttached)
                {
                    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                    Thread.GetDomain().UnhandledException += UnhandledException;
                    Application.ThreadException += Application_ThreadException;
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                }

                //HttpWebRequest.DefaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);



                Trace.TraceInformation("Starting with version {0}", SelfUpdater.CurrentVersion);

                WebRequest.DefaultWebProxy = null;
                ThreadPool.SetMaxThreads(500, 2000);
                ServicePointManager.Expect100Continue = false;
                if (Environment.OSVersion.Platform != PlatformID.Unix && !Conf.UseExternalBrowser) { Utils.SetIeCompatibility(); } //set to current IE version

                LoadConfig();


                var contentDir = !string.IsNullOrEmpty(Conf.DataFolder) ? Conf.DataFolder : StartupPath;
                if (!Directory.Exists(contentDir) || !SpringPaths.IsDirectoryWritable(contentDir) || pickInitFolder || contentDir.Contains("Local\\Apps"))
                {
                    var dc = new SelectWritableFolder() { SelectedPath = SpringPaths.GetMySpringDocPath() };
                    if (dc.ShowDialog() != DialogResult.OK) return;
                    contentDir = dc.SelectedPath;
                }
                if (Conf.DataFolder != StartupPath) Conf.DataFolder = contentDir;
                else Conf.DataFolder = null;

                if (!SpringPaths.IsDirectoryWritable(StartupPath) || StartupPath.Contains("Local\\Apps"))
                {
                    MessageBox.Show(
                        string.Format(
                            "Please use the newly created desktop icon to start Zero-K not this one.\r\nZero-K.exe will be moved to {0}",
                            contentDir), "Startup directory is not writable!");
                    var newTarget = Path.Combine(contentDir, "Zero-K.exe");
                    if (SelfUpdater.CheckForUpdate(newTarget, true))
                    {
                        Conf.Save(Path.Combine(contentDir, Config.ConfigFileName));
                        Process.Start(newTarget);
                        return;
                    }
                    MessageBox.Show("Move failed, please copy Zero-K.exe to a writable folder");
                }




                SpringPaths = new SpringPaths(null, writableFolderOverride: contentDir);
                SpringPaths.MakeFolders();
                SpringPaths.SetEnginePath(Utils.MakePath(SpringPaths.WritableDirectory, "engine", ZkData.GlobalConst.DefaultEngineOverride ?? TasClient.ServerSpringVersion));

                // run unitsync as soon as possible so we don't have to spend several minutes doing it on game start
                // two problems:
                // 1) unitsync can only be loaded once, even if in a different directory http://msdn.microsoft.com/en-us/library/ms682586.aspx#factors_that_affect_searching
                //  so if we do it in SpringVersionChanged it'll be done at startup for GlobalConst.DefaultEngineOverride, then for no other engine version
                // 2) unitsync can't be unloaded http://stackoverflow.com/questions/1371877/how-to-unload-the-dll-using-c
                // also see EngineDownload.cs
                //SpringPaths.SpringVersionChanged += (s, e) =>
                //{
                //    //System.Diagnostics.Trace.TraceInformation("SpringPaths version: {0}", SpringPaths.SpringVersion);
                //    //new PlasmaShared.UnitSyncLib.UnitSync(SpringPaths);
                //    //SpringScanner.VerifyUnitSync();
                //    //if (SpringScanner != null) SpringScanner.Dispose();
                //    //SpringScanner = new SpringScanner(SpringPaths);
                //    //SpringScanner.Start();
                //};

                SaveConfig();


                try
                {
                    if (!Debugger.IsAttached)
                    {
                        var wp = "";
                        foreach (var c in SpringPaths.WritableDirectory.Where(x => (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'))) wp += c;
                        mutex = new Mutex(false, "ZeroKLobby" + wp);
                        if (!mutex.WaitOne(10000, false))
                        {
                            MessageBox.Show(
                                "Another copy of Zero-K lobby is still running" +
                                "\nMake sure the other lobby is closed (check task manager) before starting new one",
                                "There can be only one lobby running",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Stop);
                            return;
                        }
                    }
                }
                catch (AbandonedMutexException) { }

                if (Conf.IsFirstRun)
                {
                    DialogResult result = MessageBox.Show("Create a desktop icon for Zero-K?", "Zero-K", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes) 
                    {
                        Utils.CreateDesktopShortcut();
                    }
                    if (Environment.OSVersion.Platform != PlatformID.Unix)
                        Utils.RegisterProtocol();
                }

                FriendManager = new FriendManager();
                AutoJoinManager = new AutoJoinManager();
                EngineConfigurator = new EngineConfigurator(SpringPaths.WritableDirectory);

                SpringScanner = new SpringScanner(SpringPaths);
                SpringScanner.LocalResourceAdded += (s, e) => Trace.TraceInformation("New resource found: {0}", e.Item.InternalName);
                SpringScanner.LocalResourceRemoved += (s, e) => Trace.TraceInformation("Resource removed: {0}", e.Item.InternalName);
                if (Program.Conf.EnableUnitSyncPrompt && Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    SpringScanner.UploadUnitsyncData += MicroForms.UnitSyncUploadPrompt.SpringScanner_UploadUnitsyncData;
                    SpringScanner.RetryResourceCheck += MicroForms.UnitSyncRetryPrompt.SpringScanner_RetryGetResourceInfo;
                }

                SpringScanner.MapRegistered += (s, e) => Trace.TraceInformation("Map registered: {0}", e.MapName);
                SpringScanner.ModRegistered += (s, e) => Trace.TraceInformation("Mod registered: {0}", e.Data.Name);

                Downloader = new PlasmaDownloader.PlasmaDownloader(Conf, SpringScanner, SpringPaths); //rapid
                Downloader.DownloadAdded += (s, e) => Trace.TraceInformation("Download started: {0}", e.Data.Name);

                var isLinux = Environment.OSVersion.Platform == PlatformID.Unix;
                TasClient = new TasClient(string.Format("ZK {0}{1}", SelfUpdater.CurrentVersion, isLinux ? " linux" : ""));

                SayCommandHandler = new SayCommandHandler(TasClient);

                ServerImages = new ServerImagesHandler(SpringPaths, TasClient);


                // log, for debugging
                TasClient.Connected += (s, e) => Trace.TraceInformation("TASC connected");
                TasClient.LoginAccepted += (s, e) =>
                    {
                        Trace.TraceInformation("TASC login accepted");
                        Trace.TraceInformation("Server is using Spring version {0}", TasClient.ServerSpringVersion);
                        if (Environment.OSVersion.Platform == PlatformID.Unix || Conf.UseExternalBrowser)
                            MainWindow.navigationControl.Path = "battles";
                    };

                TasClient.LoginDenied += (s, e) => Trace.TraceInformation("TASC login denied");
                TasClient.ChannelJoined += (s, e) => { Trace.TraceInformation("TASC channel joined: " + e.Data.Name); };
                TasClient.ConnectionLost += (s, e) => Trace.TraceInformation("Connection lost");

                // special handling
                TasClient.PreviewSaid += (s, e) =>
                {
                    var tas = (TasClient)s;
                    User user = null;
                    if (e.Data.UserName != null)
                    {
                        tas.ExistingUsers.TryGetValue(e.Data.UserName, out user);
                        if ((user != null && user.BanMute) || Conf.IgnoredUsers.Contains(e.Data.UserName)) e.Cancel = true;
                    }
                };

                TasClient.Extensions.JsonDataReceived += (eventArgs, o) =>
                    {
                        var command = o as ProtocolExtension.SiteToLobbyCommand;
                        if (command != null)
                        {
                            MainWindow.navigationControl.Path = command.SpringLink;
                            MainWindow.PopupSelf();
                        }
                    };

                ConnectBar = new ConnectBar(TasClient);
                ModStore = new ModStore();
                ToolTip = new ToolTipHandler();
                BrowserInterop = new BrowserInterop(TasClient, Conf);
                BattleIconManager = new BattleIconManager();

                Application.AddMessageFilter(ToolTip);


                SteamHandler = new ZklSteamHandler(TasClient);
                SteamHandler.Connect();


                MainWindow = new MainWindow();

                Application.AddMessageFilter(new ScrollMessageFilter());


                if (Conf.StartMinimized) MainWindow.WindowState = FormWindowState.Minimized;
                else MainWindow.WindowState = FormWindowState.Normal;
                MainWindow.Size = new Size(Math.Min(SystemInformation.VirtualScreen.Width - 30, MainWindow.Width),
                                            Math.Min(SystemInformation.VirtualScreen.Height - 30, MainWindow.Height)); //in case user have less space than 1024x768

                BattleBar = new BattleBar();
                NewVersionBar = new NewVersionBar(SelfUpdater);
                VoteBar = new VoteBar();
                PwBar = new PwBar();

                //This make the size of every bar constant (only for height).
                //We wanted to make them constant because the bar get DPI-scaled twice/thrice/multiple-time (especially for reusable bar). 
                //Setting maximum height upon creation will hopefully make sure it is not DPI-scaled multiple time.
                var votebarSize = new Size(0, VoteBar.Height);
                // Reference: http://stackoverflow.com/questions/5314041/set-minimum-window-size-in-c-sharp-net
                var newversionbarSize = new Size(0, NewVersionBar.Height);
                var battlebarSize = new Size(0, BattleBar.Height);
                var connectbarSize = new Size(0, ConnectBar.Height);

                VoteBar.MinimumSize = votebarSize; //fix minimum size forever
                VoteBar.MaximumSize = votebarSize; //fix maximum size forever
                NewVersionBar.MinimumSize = newversionbarSize;
                NewVersionBar.MaximumSize = newversionbarSize;
                BattleBar.MinimumSize = battlebarSize;
                BattleBar.MaximumSize = battlebarSize;
                ConnectBar.MinimumSize = connectbarSize;
                ConnectBar.MaximumSize = connectbarSize;
                //End battlebar size hax

                if (!Debugger.IsAttached && !Conf.DisableAutoUpdate) Program.SelfUpdater.StartChecking();

                //if (Conf.IsFirstRun) Utils.OpenWeb(GlobalConst.BaseSiteUrl + "/Wiki/LobbyStart", false);

                // download primary engine & game
                MainWindow.Paint += GetSpringZK;
                Downloader.PackageDownloader.MasterManifestDownloaded += GetSpringZK;


                // Format and display the TimeSpan value.
                //stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
                //Trace.TraceInformation("1 Runtime {0}", elapsedTime);




                Application.Run(MainWindow);
                ShutDown();
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleException(ex, true);
            }
            finally
            {
                ShutDown();
            }
            if (ErrorHandling.HasFatalException && !Program.CloseOnNext) Application.Restart();
        }
コード例 #23
0
        /// <summary>
        /// Starts spring game
        /// </summary>
        /// <param name="client">tasclient to get current battle from</param>
        /// <param name="priority">spring process priority</param>
        /// <param name="affinity">spring process cpu affinity</param>
        /// <param name="scriptOverride">if set, overrides generated script with supplied one</param>
        /// <param name="userName">lobby user name - used to submit score</param>
        /// <param name="passwordHash">lobby password hash - used to submit score</param>
        /// <returns>generates script</returns>
        public string StartGame(TasClient client, ProcessPriorityClass? priority, int? affinity, string scriptOverride, bool useSafeMode = false, bool useMultithreaded=false, BattleContext contextOverride = null, Battle battleOverride = null) {
            if (!File.Exists(paths.Executable) && !File.Exists(paths.DedicatedServer)) throw new ApplicationException(string.Format("Spring or dedicated server executable not found: {0}, {1}", paths.Executable, paths.DedicatedServer));

            this.client = client;
            wasKilled = false;

            if (!IsRunning) {
                gameEndedOk = false;
                IsBattleOver = false;
                lobbyUserName = client.UserName;
                lobbyPassword = client.UserPassword;
                battleResult = new BattleResult();

                talker = new Talker();
                talker.SpringEvent += talker_SpringEvent;
                var battle = battleOverride ?? client.MyBattle;
                isHosting = client != null && battle != null && battle.Founder.Name == client.MyUser.Name;

                if (isHosting) scriptPath = Utils.MakePath(paths.WritableDirectory, "script_" + battle.Founder + ".txt").Replace('\\', '/');
                else scriptPath = Utils.MakePath(paths.WritableDirectory, "script.txt").Replace('\\', '/');

                statsPlayers.Clear();
                statsData.Clear();
                StartContext = null;

                string script;
                if (!string.IsNullOrEmpty(scriptOverride)) {
                    battleResult.IsMission = true;
                    isHosting = false;
                    script = scriptOverride;
                }
                else {
                    List<UserBattleStatus> players;
                    battleGuid = Guid.NewGuid();
                    var service = GlobalConst.GetSpringieService();
                    SpringBattleStartSetup startSetup = null;
                    if (isHosting && GlobalConst.IsZkMod(battle.ModName)) {
                        try {
                            StartContext = contextOverride ?? battle.GetContext();
                            startSetup = service.GetSpringBattleStartSetup(StartContext);
                            if (startSetup.BalanceTeamsResult != null)
                            {
                                StartContext.Players = startSetup.BalanceTeamsResult.Players;
                                StartContext.Bots = startSetup.BalanceTeamsResult.Bots;
                            }
                            connectedPlayers.Clear();
                            foreach (var p in StartContext.Players)
                            {
                                p.IsIngame = true;
                            }
                        } catch (Exception ex) {
                            Trace.TraceError("Error getting start setup: {0}", ex);
                        }
                    }

                    script = battle.GenerateScript(out players, client.MyUser, talker.LoopbackPort, battleGuid.ToString(), startSetup);
                    battleResult.IsMission = battle.IsMission;
                    battleResult.IsBots = battle.Bots.Any();
                    battleResult.Title = battle.Title;
                    battleResult.Mod = battle.ModName;
                    battleResult.Map = battle.MapName;
                    battleResult.EngineVersion = paths.SpringVersion;
                    talker.SetPlayers(players);
                    statsPlayers = players.ToDictionary(x => x.Name,
                                                        x => new BattlePlayerResult
                                                                 {
                                                                     LobbyID = x.LobbyUser.AccountID,
                                                                     AllyNumber = x.AllyNumber,
                                                                     CommanderType = null,
                                                                     // todo commandertype
                                                                     IsSpectator = x.IsSpectator,
                                                                     IsVictoryTeam = false,
                                                                 });
                }
                if (isHosting) timer.Start();

                File.WriteAllText(scriptPath, script);

                LogLines = new StringBuilder();

                var optirun = Environment.GetEnvironmentVariable("OPTIRUN");

                process = new Process();
                process.StartInfo.CreateNoWindow = true;
                List<string> arg = new List<string>();


                if (string.IsNullOrEmpty(optirun))
                {
                    if (UseDedicatedServer)
                    {
                        process.StartInfo.FileName = paths.DedicatedServer;
                        process.StartInfo.WorkingDirectory = Path.GetDirectoryName(paths.DedicatedServer);
                    }
                    else
                    {
                        process.StartInfo.FileName = useMultithreaded ? paths.MtExecutable : paths.Executable;
                        process.StartInfo.WorkingDirectory = Path.GetDirectoryName(paths.Executable);
                    }
                }
                else
                {
                    Trace.TraceInformation("Using optirun {0} to start the game (OPTIRUN env var defined)", optirun);
                    process.StartInfo.FileName = optirun;
                    arg.Add(string.Format("\"{0}\"", (useMultithreaded ? paths.MtExecutable : paths.Executable)));
                }

                

                arg.Add(string.Format("--config \"{0}\"", paths.GetSpringConfigPath()));
                if (useSafeMode) arg.Add("--safemode");
                arg.Add(string.Format("\"{0}\"", scriptPath));
                //Trace.TraceInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

                process.StartInfo.Arguments = string.Join(" ", arg);
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.Exited += springProcess_Exited;
                process.ErrorDataReceived += process_ErrorDataReceived;
                process.OutputDataReceived += process_OutputDataReceived;
                process.EnableRaisingEvents = true;

                gamePrivateMessages = new Dictionary<string, int>();
                battleResult.StartTime = DateTime.UtcNow;
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                if (IsRunning && SpringStarted != null) SpringStarted(this, EventArgs.Empty);

                Utils.StartAsync(() =>
                    {
                        Thread.Sleep(1000);
                        try {
                            if (priority != null) process.PriorityClass = priority.Value;
                            if (affinity != null) process.ProcessorAffinity = (IntPtr)affinity.Value;
                        } catch (Exception ex) {
                            Trace.TraceWarning("Error setting spring process affinity: {0}", ex);
                        }
                    });

                return script;
            }
            else Trace.TraceError("Spring already running");
            return null;
        }
コード例 #24
0
 public AbstractPoll(TasClient tas, Spring spring, AutoHost ah) {
     this.tas = tas;
     this.spring = spring;
     this.ah = ah;
 }
コード例 #25
0
 public NightwatchTraceListener(TasClient tas)
 {
     this.tas = tas;
 }
コード例 #26
0
        public AutoHost(MetaDataCache cache, AhConfig config, int hostingPort, SpawnConfig spawn)
        {
            this.config      = config;
            Commands         = new CommandList(config);
            this.cache       = cache;
            SpawnConfig      = spawn;
            this.hostingPort = hostingPort;

            string version = config.SpringVersion ?? Program.main.Config.SpringVersion ?? tas.ServerSpringVersion; // tas empty at this point! Possible null exception

            springPaths = new SpringPaths(Program.main.paths.GetEngineFolderByVersion(version), writableFolderOverride: Program.main.Config.DataDir);

            Program.main.paths.SpringVersionChanged += (s, e) =>
            {
                if (!String.IsNullOrEmpty(requestedEngineChange) && requestedEngineChange == Program.main.paths.SpringVersion)
                {
                    config.SpringVersion = requestedEngineChange;
                    springPaths.SetEnginePath(Program.main.paths.GetEngineFolderByVersion(requestedEngineChange));
                    requestedEngineChange = null;

                    tas.Say(TasClient.SayPlace.Battle, "", "rehosting to engine version " + springPaths.SpringVersion, true);
                    ComRehost(TasSayEventArgs.Default, new string[] { });
                }
            };

            spring = new Spring(springPaths)
            {
                UseDedicatedServer = true
            };
            bool isManaged = SpawnConfig == null && config.Mode != AutohostMode.None;

            tas = new TasClient(null,
                                MainConfig.SpringieVersion,
                                isManaged ? GlobalConst.ZkSpringieManagedCpu : GlobalConst.ZkLobbyUserCpu,
                                false,
                                Program.main.Config.IpOverride);

            pollTimer           = new Timer(PollTimeout * 1000);
            pollTimer.Enabled   = false;
            pollTimer.AutoReset = false;
            pollTimer.Elapsed  += pollTimer_Elapsed;

            spring.SpringExited += spring_SpringExited;
            spring.GameOver     += spring_GameOver;

            spring.SpringExited  += spring_SpringExited;
            spring.SpringStarted += spring_SpringStarted;
            spring.PlayerSaid    += spring_PlayerSaid;
            spring.BattleStarted += spring_BattleStarted;

            tas.BattleUserLeft          += tas_BattleUserLeft;
            tas.UserStatusChanged       += tas_UserStatusChanged;
            tas.BattleUserStatusChanged += TasOnBattleUserStatusChanged;
            tas.BattleUserJoined        += tas_BattleUserJoined;
            tas.MyBattleMapChanged      += tas_MyBattleMapChanged;
            tas.BattleLockChanged       += tas_BattleLockChanged;
            tas.BattleOpened            += tas_BattleOpened;
            tas.UserAdded += (o, u) => { if (u.Data.Name == GetAccountName())
                                         {
                                             Start(null, null);
                                         }
            };

            tas.RegistrationDenied += (s, e) =>
            {
                ErrorHandling.HandleException(null, "Registration denied: " + e.ServerParams[0]);
                CloneNumber++;
                tas.Login(GetAccountName(), config.Password);
            };

            tas.RegistrationAccepted += (s, e) => tas.Login(GetAccountName(), config.Password);

            tas.AgreementRecieved += (s, e) =>
            {
                tas.AcceptAgreement();

                PlasmaShared.Utils.SafeThread(() =>
                {
                    Thread.Sleep(7000);
                    tas.Login(GetAccountName(), config.Password);
                }).Start();
            };

            tas.ConnectionLost  += tas_ConnectionLost;
            tas.Connected       += tas_Connected;
            tas.LoginDenied     += tas_LoginDenied;
            tas.LoginAccepted   += tas_LoginAccepted;
            tas.Said            += tas_Said;
            tas.MyBattleStarted += tas_MyStatusChangedToInGame;

            linkProvider = new ResourceLinkProvider(this);

            tas.Connect(Program.main.Config.ServerHost, Program.main.Config.ServerPort);

            Program.main.Downloader.PackagesChanged += Downloader_PackagesChanged;

            timer          = new Timer(15000);
            timer.Elapsed += (s, e) =>
            {
                try {
                    timer.Stop();
                    timerTick++;

                    // auto update engine branch
                    if (!String.IsNullOrEmpty(config.AutoUpdateSpringBranch) && timerTick % 4 == 0)
                    {
                        CheckEngineBranch();
                    }

                    // auto verify pw map
                    if (!spring.IsRunning && config.Mode != AutohostMode.None)
                    {
                        if (SpawnConfig == null && config.Mode == AutohostMode.Planetwars)
                        {
                            ServerVerifyMap(false);
                        }
                    }

                    // auto start split vote
                    if (!spring.IsRunning && config.SplitBiggerThan != null && tas.MyBattle != null && config.SplitBiggerThan < tas.MyBattle.NonSpectatorCount)
                    {
                        if (DateTime.Now.Subtract(spring.GameExited).TotalSeconds >= GameExitSplitDelay)
                        {
                            ComSplitPlayers(TasSayEventArgs.Default, new string[] {});
                        }

                        /*
                         * int cnt = tas.MyBattle.NonSpectatorCount;
                         * if (cnt > lastSplitPlayersCountCalled && cnt%2 == 0) {
                         *  StartVote(new VoteSplitPlayers(tas, spring, this), TasSayEventArgs.Default, new string[] { });
                         *  lastSplitPlayersCountCalled = cnt;
                         * }*/
                    }

                    // auto rehost to latest mod version
                    if (!string.IsNullOrEmpty(config.AutoUpdateRapidTag) && SpawnConfig == null)
                    {
                        UpdateRapidMod(config.AutoUpdateRapidTag);
                    }

                    if (lockedUntil != DateTime.MinValue && lockedUntil < DateTime.Now)
                    {
                        ComUnlock(TasSayEventArgs.Default, new string[] {});
                    }
                } catch (Exception ex) {
                    Trace.TraceError(ex.ToString());
                } finally {
                    timer.Start();
                }
            };
            timer.Start();
        }
コード例 #27
0
        /// <summary>
        /// singleton, dont use, internal for designer
        /// </summary>
        internal BattleBar()
        {
            InitializeComponent();

            Program.ToolTip.SetText(btnLeave, "Leave this battle");

            picoChat.ChatBackgroundColor = TextColor.background; //same color as Program.Conf.BgColor
            picoChat.IRCForeColor        = 14;                   //mirc grey. Unknown use
            picoChat.DefaultTooltip      = "Last lines from room chat, click to enter full screen chat";

            gameBox.BackColor          = Color.Transparent;
            btnStart.Image             = Buttons.fight.GetResizedWithCache(38, 38);
            btnStart.ImageAlign        = ContentAlignment.MiddleCenter;
            btnStart.TextImageRelation = TextImageRelation.ImageAboveText;
            btnStart.Text = "Play";

            btnLeave.Image             = Buttons.exit.GetResizedWithCache(38, 38);
            btnLeave.ImageAlign        = ContentAlignment.MiddleCenter;
            btnLeave.TextImageRelation = TextImageRelation.ImageAboveText;
            btnLeave.Text = "Leave";

            Program.ToolTip?.SetText(btnStart, "Start battle");
            Program.ToolTip?.SetText(btnLeave, "Quit battle");

            picoChat.Visible = false;


            btnStart.Click += btnStart_Click;
            btnLeave.Click += BtnLeaveClick;

            client = Program.TasClient;
            spring = new Spring(Program.SpringPaths);


            try
            {
                // silly way to create speech and voice engines on runtime - needed due to mono crash
                speech = Activator.CreateInstance(Type.GetType("ZeroKLobby.ChatToSpeech"), spring);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Failed to init VoiceCommands:{0}", ex.Message);
            }

            spring.SpringExited += (s, e) =>
            {
                client.ChangeMyUserStatus(isInGame: false);

                if (e.IsCrash)
                {
                    Program.MainWindow.InvokeFunc(() =>
                    {
                        var defaultButton = MessageBoxDefaultButton.Button2;
                        var icon          = MessageBoxIcon.None;
                        if (
                            MessageBox.Show(this, "Do you want me to set Low details?\n(will effect: lups.cfg and springsettings.cfg)\n\nIf you wish to file a bug report, please include a copy of infolog.txt in your game data folder (accessible through Settings).\nUpload it to a text sharing site such as pastebin.com.",
                                            "Spring engine has crashed, update your video and audio drivers please!",
                                            MessageBoxButtons.YesNo,
                                            icon,
                                            defaultButton) == DialogResult.Yes)
                        {
                            Program.Conf.UseSafeMode = true;
                            Program.EngineConfigurator.Configure(true, 0);
                        }
                    });
                }
            };

            spring.SpringStarted += (s, e) =>
            {
                Program.MainWindow.SwitchMusicOnOff(false);
                client.ChangeMyUserStatus(isInGame: true);
            };

            client.Rang += (s, e) =>
            {
                if (e.Place == SayPlace.Channel)
                {
                    MainWindow.Instance.NotifyUser($"chat/{e.Target}", $"Attention needed in {e.Target} channel", true, true);
                }
                else
                {
                    MainWindow.Instance.NotifyUser("chat/battle", "Someone demands your attention in battle room!", true, true);
                    AutoRespond();
                }
            };



            client.BattleJoinSuccess += (s, e) =>
            {
                if (!isVisible)
                {
                    ManualBattleStarted();
                }
                if (IsHostGameRunning())
                {
                    btnStart.Text = "Rejoin";
                }
                else
                {
                    btnStart.Text = "Start";
                }


                //client.ChangeMyUserStatus(false, false);
                var battle = client.MyBattle;
                lastBattleFounder = battle.FounderName;

                //Title = string.Format("Joined battle room hosted by {0}", battle.Founder.Name);
                //TitleTooltip = "Use button on the left side to start a game";
                radioPlay.Visible = true;
                radioSpec.Visible = true;
                btnStart.Visible  = true;

                Program.Downloader.GetResource(DownloadType.MAP, battle.MapName);
                Program.Downloader.GetResource(DownloadType.RAPID, battle.ModName);
                Program.Downloader.GetResource(DownloadType.ENGINE, battle.EngineVersion);

                if (gameBox.Image != null)
                {
                    gameBox.Image.Dispose();
                }
                CreateBattleIcon(Program.BattleIconManager.GetBattleIcon(battle.BattleID));

                RefreshTooltip();

                if (Program.TasClient.MyBattle != null)
                {
                    NavigationControl.Instance.Path = "chat/battle";
                }

                client.ChangeMyBattleStatus(desiredSpectatorState, HasAllResources() ? SyncStatuses.Synced : SyncStatuses.Unsynced, 0);
            };


            client.MyBattleMapChanged += (s, e) =>
            {
                if (client.MyBattle != null && !Program.SpringScanner.HasResource(client.MyBattle.MapName))
                {
                    client.ChangeMyBattleStatus(syncStatus: SyncStatuses.Unsynced);
                    Program.Downloader.GetResource(DownloadType.MAP, client.MyBattle.MapName);
                }
                RefreshTooltip();
            };

            client.MyBattleHostExited += (s, e) => { btnStart.Text = "Start"; };

            client.ConnectSpringReceived += (s, e) =>
            {
                try
                {
                    btnStart.Text = "Rejoin";

                    List <Download> downloads = new List <Download>();
                    downloads.Add(Program.Downloader.GetResource(DownloadType.ENGINE, e.Engine));
                    downloads.Add(Program.Downloader.GetResource(DownloadType.RAPID, e.Game));
                    downloads.Add(Program.Downloader.GetResource(DownloadType.MAP, e.Map));
                    downloads = downloads.Where(x => x != null).ToList();
                    if (downloads.Count > 0)
                    {
                        var dd = new WaitDownloadDialog(downloads);
                        if (dd.ShowDialog(Program.MainWindow) == DialogResult.Cancel)
                        {
                            return;
                        }
                    }

                    if (spring.IsRunning)
                    {
                        spring.ExitGame();
                    }
                    spring.ConnectGame(e.Ip, e.Port, client.UserName, e.ScriptPassword, e.Engine);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Error starting spring: " + ex.Message);
                }
                RefreshTooltip();
            };

            client.BattleMyUserStatusChanged += (s, e) =>
            {
                if (client.MyBattleStatus != null)
                {
                    //btnStart.Enabled = client.MyBattleStatus.SyncStatus == SyncStatuses.Synced;

                    if (client.MyBattleStatus.IsSpectator && radioPlay.Checked)
                    {
                        ChangeGuiSpectatorWithoutEvent(false);                                                             // i was spectated
                    }
                    if (!client.MyBattleStatus.IsSpectator && radioSpec.Checked)
                    {
                        ChangeGuiSpectatorWithoutEvent(true);                                                              //i was unspectated
                    }
                }
            };

            client.BattleClosed += (s, e) =>
            {
                btnStart.Text = "Start";
                if (gameBox.Image != null)
                {
                    gameBox.Image.Dispose();
                }
                gameBox.Image = null;
                RefreshTooltip();
                Stop();
            };

            client.MyBattleRemoved += (s, e) =>
            {
                var t        = new Timer();
                var tryCount = 0;
                t.Interval = 1000;
                t.Tick    += (s2, e2) =>
                {
                    tryCount++;
                    if (tryCount > 15)
                    {
                        t.Stop();
                        t.Dispose();
                    }
                    else if (client.IsLoggedIn && client.MyBattle == null)
                    {
                        var bat = client.ExistingBattles.Values.FirstOrDefault(x => x.FounderName == lastBattleFounder && !x.IsPassworded);
                        if (bat != null)
                        {
                            ActionHandler.JoinBattle(bat.BattleID, null);
                            t.Stop();
                            t.Dispose();
                        }
                    }
                };
                t.Start();
            };

            client.ConnectionLost += (s, e) =>
            {
                if (gameBox.Image != null)
                {
                    gameBox.Image.Dispose();
                }
                gameBox.Image = null;
                RefreshTooltip();
                Stop();
            };



            timer.Tick += (s, e) =>
            {
                if (client.IsLoggedIn)
                {
                    if (WindowsApi.IdleTime.TotalMinutes > Program.Conf.IdleTime)
                    {
                        if (!client.MyUser.IsAway)
                        {
                            client.ChangeMyUserStatus(isAway: true);
                        }
                    }
                    else
                    {
                        if (client.MyUser.IsAway)
                        {
                            client.ChangeMyUserStatus(isAway: false);
                        }
                    }
                    CheckMyBattle();
                }
            };


            Program.MainWindow.navigationControl.PageChanged += s =>
            {
                if (s != "chat/battle")
                {
                    picoChat.Visible = true;
                }
                else
                {
                    picoChat.Visible = false;
                }
            };

            timer.Interval = 2000;
            timer.Start();

            Program.BattleIconManager.BattleChanged += BattleIconManager_BattleChanged;

            //picoChat.Font = new Font(Program.Conf.ChatFont.FontFamily, Program.Conf.ChatFont.Size*0.8f);
            picoChat.ShowHistory   = false;
            picoChat.ShowJoinLeave = false;
            //picoChat.HideScroll = true;

            BattleChatControl.BattleLine += (s, e) => picoChat.AddLine(e.Data);

            picoChat.MouseClick += (s, e) => NavigationControl.Instance.Path = "chat/battle";
        }
コード例 #28
0
 public VoteResign(TasClient tas, Spring spring, AutoHost ah) : base(tas, spring, ah)
 {
 }
コード例 #29
0
        public bool Start()
        {
            if (config.AttemptToRecconnect)
            {
                recon          = new System.Timers.Timer(config.AttemptReconnectInterval * 1000);
                recon.Elapsed += new ElapsedEventHandler(recon_Elapsed);
            }

            recon.Enabled = false;

            try {
                spring = new Spring(config.SpringPath);
            } catch {
                MessageBox.Show("Spring not found in " + config.SpringPath, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                OpenFileDialog od = new OpenFileDialog();
                od.FileName         = Spring.ExecutableName;
                od.DefaultExt       = Path.GetExtension(Spring.ExecutableName);
                od.InitialDirectory = config.SpringPath;
                od.Title            = "Please select your spring installation";
                od.RestoreDirectory = true;
                od.CheckFileExists  = true;
                od.CheckPathExists  = true;
                od.AddExtension     = true;
                od.Filter           = "Executable (*.exe)|*.exe";
                DialogResult dr = od.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    config.SpringPath = Path.GetDirectoryName(od.FileName);
                    SaveConfig();
                    try {
                        spring = new Spring(config.SpringPath);
                    } catch (Exception e) {
                        MessageBox.Show(e.ToString(), "Error while checking spring, exiting");
                        Application.Exit();
                        return(false);
                    }
                }
                else
                {
                    MessageBox.Show("Spring not found, exiting");
                    Application.Exit();
                    return(false);
                }
            }


            tas = new TasClient();
            tas.ConnectionLost          += new EventHandler <TasEventArgs>(tas_ConnectionLost);
            tas.Connected               += new EventHandler <TasEventArgs>(tas_Connected);
            tas.LoginDenied             += new EventHandler <TasEventArgs>(tas_LoginDenied);
            tas.LoginAccepted           += new EventHandler <TasEventArgs>(tas_LoginAccepted);
            tas.Said                    += new EventHandler <TasSayEventArgs>(tas_Said);
            tas.MyStatusChangedToInGame += new EventHandler <TasEventArgs>(tas_MyStatusChangedToInGame);
            spring.SpringExited         += new EventHandler(spring_SpringExited);
            spring.PlayerSaid           += new EventHandler <SpringLogEventArgs>(spring_PlayerSaid);
            autoHost                     = new AutoHost(tas, spring, null);
            autoUpdater                  = new AutoUpdater(spring, tas);

            if (config.StatsEnabled)
            {
                stats = new Stats(tas, spring);
            }
            try {
                tas.Connect(config.ServerHost, config.ServerPort);
            } catch {
                recon.Start();
            }
            return(true);
        }
コード例 #30
0
 public VotePreset(TasClient tas, Spring spring, AutoHost ah) : base(tas, spring, ah)
 {
 }
コード例 #31
0
        public AutoHost(MetaDataCache cache, AhConfig config, int hostingPort, SpawnConfig spawn)
        {
            this.config      = config;
            Commands         = new CommandList(config);
            this.cache       = cache;
            SpawnConfig      = spawn;
            this.hostingPort = hostingPort;


            string version = config.SpringVersion ?? Program.main.Config.SpringVersion ?? GlobalConst.DefaultEngineOverride;

            springPaths = new SpringPaths(Program.main.paths.GetEngineFolderByVersion(version), Program.main.Config.DataDir);

            springPaths.SpringVersionChanged += (s, e) =>
            {
                if (!String.IsNullOrEmpty(requestedEngineChange) && requestedEngineChange == springPaths.SpringVersion)
                {
                    config.SpringVersion = requestedEngineChange;
                    springPaths.SetEnginePath(Program.main.paths.GetEngineFolderByVersion(requestedEngineChange));
                    requestedEngineChange = null;

                    tas.Say(SayPlace.Battle, "", "rehosting to engine version " + springPaths.SpringVersion, true);
                    ComRehost(TasSayEventArgs.Default, new string[] { });
                }
            };

            spring = new Spring(springPaths)
            {
                UseDedicatedServer = true
            };
            bool isManaged = SpawnConfig == null && config.Mode != AutohostMode.None;

            tas = new TasClient(MainConfig.SpringieVersion,
                                isManaged ? Login.ClientTypes.SpringieManaged : Login.ClientTypes.Springie,
                                Program.main.Config.IpOverride);

            pollTimer           = new Timer(PollTimeout * 1000);
            pollTimer.Enabled   = false;
            pollTimer.AutoReset = false;
            pollTimer.Elapsed  += pollTimer_Elapsed;

            spring.SpringExited += spring_SpringExited;
            spring.GameOver     += spring_GameOver;

            spring.SpringExited  += spring_SpringExited;
            spring.SpringStarted += spring_SpringStarted;
            spring.PlayerSaid    += spring_PlayerSaid;
            spring.BattleStarted += spring_BattleStarted;

            tas.BattleUserLeft     += tas_BattleUserLeft;
            tas.UserStatusChanged  += tas_UserStatusChanged;
            tas.BattleUserJoined   += tas_BattleUserJoined;
            tas.MyBattleMapChanged += tas_MyBattleMapChanged;
            tas.BattleOpened       += tas_BattleOpened;
            tas.UserAdded          += (o, u) => { if (u.Name == GetAccountName())
                                                  {
                                                      OpenBattleRoom(null, null);
                                                  }
            };

            tas.RegistrationDenied += (s, e) =>
            {
                Trace.TraceWarning("Registration denied: {0} {1}", e.ResultCode.Description(), e.Reason);
                CloneNumber++;
                tas.Login(GetAccountName(), config.Password);
            };

            tas.RegistrationAccepted += (s, e) => tas.Login(GetAccountName(), config.Password);

            tas.ConnectionLost  += tas_ConnectionLost;
            tas.Connected       += tas_Connected;
            tas.LoginDenied     += tas_LoginDenied;
            tas.LoginAccepted   += tas_LoginAccepted;
            tas.Said            += tas_Said;
            tas.MyBattleStarted += tas_MyStatusChangedToInGame;

            linkSpringieClient = new ResourceLinkSpringieClient(this);

            // queue autohost
            if (config != null && config.MinToJuggle != null && SpawnConfig == null)
            {
                queue = new MatchMakerQueue(this);
            }


            Program.main.Downloader.PackagesChanged += Downloader_PackagesChanged;

            timer          = new Timer(15000);
            timer.Elapsed += (s, e) =>
            {
                try {
                    timer.Stop();
                    timerTick++;

                    // auto update engine branch
                    if (!String.IsNullOrEmpty(config.AutoUpdateSpringBranch) && timerTick % 4 == 0)
                    {
                        CheckEngineBranch();
                    }

                    // auto verify pw map
                    if (!spring.IsRunning && config.Mode != AutohostMode.None)
                    {
                        if (SpawnConfig == null && config.Mode == AutohostMode.Planetwars)
                        {
                            ServerVerifyMap(false);
                        }
                    }

                    // auto start split vote
                    if (!spring.IsRunning && config.SplitBiggerThan != null && tas.MyBattle != null && config.SplitBiggerThan < tas.MyBattle.NonSpectatorCount)
                    {
                        if (DateTime.Now.Subtract(spring.GameExited).TotalSeconds >= GameExitSplitDelay)
                        {
                            ComSplitPlayers(TasSayEventArgs.Default, new string[] {});
                        }

                        /*
                         * int cnt = tas.MyBattle.NonSpectatorCount;
                         * if (cnt > lastSplitPlayersCountCalled && cnt%2 == 0) {
                         *  StartVote(new VoteSplitPlayers(tas, spring, this), TasSayEventArgs.Default, new string[] { });
                         *  lastSplitPlayersCountCalled = cnt;
                         * }*/
                    }

                    // auto rehost to latest mod version
                    if (!string.IsNullOrEmpty(config.AutoUpdateRapidTag) && SpawnConfig == null)
                    {
                        UpdateRapidMod(config.AutoUpdateRapidTag);
                    }
                } catch (Exception ex) {
                    Trace.TraceError(ex.ToString());
                } finally {
                    timer.Start();
                }
            };
            timer.Start();
        }
コード例 #32
0
        /// <summary>
        /// singleton, dont use, internal for designer
        /// </summary>
        internal BattleBar()
        {
            InitializeComponent();

            Program.ToolTip.SetText(btnLeave, "Leave this battle");

            picoChat.ChatBackgroundColor = TextColor.background; //same color as Program.Conf.BgColor
            picoChat.IRCForeColor = 14; //mirc grey. Unknown use
            picoChat.DefaultTooltip = "Last lines from room chat, click to enter full screen chat";

            gameBox.BackColor = Color.Transparent;
            btnStart.Image = Buttons.fight.GetResizedWithCache(38, 38);
            btnStart.ImageAlign = ContentAlignment.MiddleCenter;
            btnStart.TextImageRelation = TextImageRelation.ImageAboveText;
            btnStart.Text = "Play";

            btnLeave.Image = Buttons.exit.GetResizedWithCache(38, 38);
            btnLeave.ImageAlign = ContentAlignment.MiddleCenter;
            btnLeave.TextImageRelation = TextImageRelation.ImageAboveText;
            btnLeave.Text = "Leave";

            Program.ToolTip?.SetText(btnStart, "Start battle");
            Program.ToolTip?.SetText(btnLeave, "Quit battle");

            picoChat.Visible = false;


            btnStart.Click += btnStart_Click;
            btnLeave.Click += BtnLeaveClick;

            client = Program.TasClient;
            spring = new Spring(Program.SpringPaths);


            try
            {
                // silly way to create speech and voice engines on runtime - needed due to mono crash
                speech = Activator.CreateInstance(Type.GetType("ZeroKLobby.ChatToSpeech"), spring);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Failed to init VoiceCommands:{0}", ex.Message);
            }

            spring.SpringExited += (s, e) =>
                {
                    client.ChangeMyUserStatus(isInGame: false);

                    if (e.IsCrash)
                    {
                        Program.MainWindow.InvokeFunc(() =>
                            {
                                var defaultButton = MessageBoxDefaultButton.Button2;
                                var icon = MessageBoxIcon.None;
                                if (
                                    MessageBox.Show(this, "Do you want me to set Low details?\n(will effect: lups.cfg and springsettings.cfg)\n\nIf you wish to file a bug report, please include a copy of infolog.txt in your game data folder (accessible through Settings).\nUpload it to a text sharing site such as pastebin.com.",
                                                    "Spring engine has crashed, update your video and audio drivers please!",
                                                    MessageBoxButtons.YesNo,
                                                    icon,
                                                    defaultButton) == DialogResult.Yes)
                                {
                                    Program.Conf.UseSafeMode = true;
                                    Program.EngineConfigurator.Configure(true, 0);
                                }
                            });
                    }
                };

            spring.SpringStarted += (s, e) =>
            {
                Program.MainWindow.SwitchMusicOnOff(false);
                client.ChangeMyUserStatus(isInGame: true);
            };

            client.Rang += (s, e) =>
                {
                    if (e.Place == SayPlace.Channel)
                        MainWindow.Instance.NotifyUser($"chat/{e.Target}", $"Attention needed in {e.Target} channel", true, true);
                    else 
                    {
                        MainWindow.Instance.NotifyUser("chat/battle", "Someone demands your attention in battle room!", true, true);
                        AutoRespond();
                    }
                };



            client.BattleJoined += (s, e) =>
                {
                    if (!isVisible) ManualBattleStarted();
                    if (IsHostGameRunning()) btnStart.Text = "Rejoin";
                    else btnStart.Text = "Start";


                    //client.ChangeMyUserStatus(false, false);
                    var battle = client.MyBattle;
                    lastBattleFounder = battle.FounderName;

                    //Title = string.Format("Joined battle room hosted by {0}", battle.Founder.Name);
                    //TitleTooltip = "Use button on the left side to start a game";
                    radioPlay.Visible = true;
                    radioSpec.Visible = true;
                    btnStart.Visible = true;

                    Program.Downloader.GetResource(DownloadType.MAP, battle.MapName);
                    Program.Downloader.GetResource(DownloadType.MOD, battle.ModName);
                    Program.Downloader.GetResource(DownloadType.ENGINE, battle.EngineVersion);

                    if (gameBox.Image != null) gameBox.Image.Dispose();
                    CreateBattleIcon(Program.BattleIconManager.GetBattleIcon(battle.BattleID));

                    RefreshTooltip();

                    if (Program.TasClient.MyBattle != null) NavigationControl.Instance.Path = "chat/battle";

                    client.ChangeMyBattleStatus(desiredSpectatorState, HasAllResources() ? SyncStatuses.Synced : SyncStatuses.Unsynced, 0);
                };


            client.MyBattleMapChanged += (s, e) =>
                {
                    if (client.MyBattle != null && !Program.SpringScanner.HasResource(client.MyBattle.MapName))
                    {
                        client.ChangeMyBattleStatus(syncStatus: SyncStatuses.Unsynced);
                        Program.Downloader.GetResource(DownloadType.MAP, client.MyBattle.MapName);
                    }
                    RefreshTooltip();
                };

            client.MyBattleHostExited += (s, e) => { btnStart.Text = "Start"; };

            client.ConnectSpringReceived += (s, e) =>
            {
                try
                {
                    btnStart.Text = "Rejoin";

                    List<Download> downloads = new List<Download>();
                    downloads.Add(Program.Downloader.GetResource(DownloadType.ENGINE, e.Engine));
                    downloads.Add(Program.Downloader.GetResource(DownloadType.MOD, e.Game));
                    downloads.Add(Program.Downloader.GetResource(DownloadType.MAP, e.Map));
                    downloads = downloads.Where(x => x != null).ToList();
                    if (downloads.Count > 0)
                    {
                        var dd = new WaitDownloadDialog(downloads);
                        if (dd.ShowDialog(Program.MainWindow) == DialogResult.Cancel) return;
                    }
                    
                    if (spring.IsRunning) spring.ExitGame();
                    spring.ConnectGame(e.Ip, e.Port, client.UserName, e.ScriptPassword, e.Engine);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Error starting spring: " + ex.Message);
                }
                RefreshTooltip();
            };

            client.BattleMyUserStatusChanged += (s, e) =>
                {
                    if (client.MyBattleStatus != null)
                    {
                        //btnStart.Enabled = client.MyBattleStatus.SyncStatus == SyncStatuses.Synced;

                        if (client.MyBattleStatus.IsSpectator && radioPlay.Checked) ChangeGuiSpectatorWithoutEvent(false); // i was spectated
                        if (!client.MyBattleStatus.IsSpectator && radioSpec.Checked) ChangeGuiSpectatorWithoutEvent(true); //i was unspectated
                    }
                };

            client.BattleClosed += (s, e) =>
                {
                    btnStart.Text = "Start";
                    if (gameBox.Image != null) gameBox.Image.Dispose();
                    gameBox.Image = null;
                    RefreshTooltip();
                    Stop();
                };

            client.MyBattleRemoved += (s, e) =>
                {
                    var t = new Timer();
                    var tryCount = 0;
                    t.Interval = 1000;
                    t.Tick += (s2, e2) =>
                        {
                            tryCount++;
                            if (tryCount > 15)
                            {
                                t.Stop();
                                t.Dispose();
                            }
                            else if (client.IsLoggedIn && client.MyBattle == null)
                            {
                                var bat = client.ExistingBattles.Values.FirstOrDefault(x => x.FounderName == lastBattleFounder && !x.IsPassworded);
                                if (bat != null)
                                {
                                    ActionHandler.JoinBattle(bat.BattleID, null);
                                    t.Stop();
                                    t.Dispose();
                                }
                            }
                        };
                    t.Start();
                };

            client.ConnectionLost += (s, e) =>
                {
                    if (gameBox.Image != null) gameBox.Image.Dispose();
                    gameBox.Image = null;
                    RefreshTooltip();
                    Stop();
                };



            timer.Tick += (s, e) =>
                {
                    if (client.IsLoggedIn)
                    {
                        if (WindowsApi.IdleTime.TotalMinutes > Program.Conf.IdleTime)
                        {
                            if (!client.MyUser.IsAway) client.ChangeMyUserStatus(isAway: true);
                        }
                        else
                        {
                            if (client.MyUser.IsAway) client.ChangeMyUserStatus(isAway: false);
                        }
                        CheckMyBattle();
                    }
                };


            Program.MainWindow.navigationControl.PageChanged += s =>
            {
                if (s != "chat/battle")
                {
                    picoChat.Visible = true;
                }
                else picoChat.Visible = false;
            };

            timer.Interval = 1000;
            timer.Start();

            Program.BattleIconManager.BattleChanged += BattleIconManager_BattleChanged;

            //picoChat.Font = new Font(Program.Conf.ChatFont.FontFamily, Program.Conf.ChatFont.Size*0.8f);
            picoChat.ShowHistory = false;
            picoChat.ShowJoinLeave = false;
            //picoChat.HideScroll = true;

            BattleChatControl.BattleLine += (s, e) => picoChat.AddLine(e.Data);

            picoChat.MouseClick += (s, e) => NavigationControl.Instance.Path = "chat/battle";
        }
コード例 #33
0
        /// <summary>
        /// singleton, dont use, internal for designer
        /// </summary>
        internal BattleBar()
        {
            InitializeComponent();

            picoChat.ChatBackgroundColor = TextColor.background; //same color as Program.Conf.BgColor
            picoChat.IRCForeColor = 14; //mirc grey. Unknown use

            picoChat.DefaultTooltip = "Last lines from room chat, click to enter full screen chat";

            client = Program.TasClient;
            spring = new Spring(Program.SpringPaths);


            try
            {
                // silly way to create speech and voice engines on runtime - needed due to mono crash
                speech = Activator.CreateInstance(Type.GetType("ZeroKLobby.ChatToSpeech"), spring);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Failed to init VoiceCommands:{0}", ex.Message);
            }

            spring.SpringExited += (s, e) =>
                {
                    client.ChangeMyUserStatus(isInGame: false);

                    if (e.Data)
                    {
                        Program.MainWindow.InvokeFunc(() =>
                            {
                                var defaultButton = MessageBoxDefaultButton.Button2;
                                var icon = MessageBoxIcon.None;
                                if (
                                    MessageBox.Show("Do you want me to set Low details?\n(will effect: lups.cfg and springsettings.cfg)\n\nIf you wish to file a bug report, please include a copy of infolog.txt in your game data folder (accessible through Settings).\nUpload it to a text sharing site such as pastebin.com.",
                                                    "Spring engine has crashed, update your video and audio drivers please!",
                                                    MessageBoxButtons.YesNo,
                                                    icon,
                                                    defaultButton) == DialogResult.Yes)
                                {
                                    Program.Conf.UseSafeMode = true;
                                    Program.EngineConfigurator.Configure(true, 0);
                                }
                            });
                    }
                };

            spring.SpringStarted += (s, e) =>
            {
                Program.MainWindow.SwitchMusicOnOff(false);
                client.ChangeMyUserStatus(isInGame: true);
            };

            client.Rang += (s, e) =>
                {
                    if (e.User == GlobalConst.NightwatchName)
                        //Nightwatch RING is from UserController.cs (website code)
                        MainWindow.Instance.NotifyUser("chat/zkadmin", "New report arrive at zkadmin channel", true, true);
                    else
                    {
                        MainWindow.Instance.NotifyUser("chat/battle", "Someone demands your attention in battle room!", true, true);
                        AutoRespond();
                    }
                };

            client.BattleJoined += (s, e) =>
                {
                    if (!isVisible) ManualBattleStarted();
                    if (IsHostGameRunning()) barContainer.btnDetail.Text = "Rejoin";
                    else barContainer.btnDetail.Text = "Start";
                    //client.ChangeMyUserStatus(false, false);
                    var battle = client.MyBattle;
                    lastBattleFounder = battle.Founder.Name;

                    if (battle.Founder.Name.StartsWith("PlanetWars") || battle.Founder.Name.StartsWith("Zk")) ChangeDesiredSpectatorState(false); // TODO pw unpsec hack, remove later

                    if (battle.IsQueue)
                    {
                        barContainer.Title = string.Format("Joined {0} Quick Match Queue", battle.QueueName);
                        barContainer.TitleTooltip = "Please await people, game will start automatically";
                        lbQueue.Visible = true;
                        radioPlay.Visible = false;
                        radioSpec.Visible = false;
                        barContainer.btnDetail.Visible = false;
                    }
                    else
                    {
                        barContainer.Title = string.Format("Joined battle room hosted by {0}", battle.Founder.Name);
                        barContainer.TitleTooltip = "Use button on the left side to start a game";
                        lbQueue.Visible = false;
                        radioPlay.Visible = true;
                        radioSpec.Visible = true;
                        barContainer.btnDetail.Visible = true;
                    }

                    Program.Downloader.GetResource(DownloadType.MAP, battle.MapName);
                    Program.Downloader.GetResource(DownloadType.MOD, battle.ModName);
                    engineVersionNeeded = battle.EngineVersion;
                    if (engineVersionNeeded != Program.SpringPaths.SpringVersion) Program.Downloader.GetAndSwitchEngine(engineVersionNeeded);
                    else engineVersionNeeded = null;

                    if (gameBox.Image != null) gameBox.Image.Dispose();
                    DpiMeasurement.DpiXYMeasurement(this);
                    int scaledIconHeight = DpiMeasurement.ScaleValueY(BattleIcon.Height);
                    int scaledIconWidth = DpiMeasurement.ScaleValueX(BattleIcon.Width);
                    gameBox.Image = new Bitmap(scaledIconWidth, scaledIconHeight);
                    using (var g = Graphics.FromImage(gameBox.Image))
                    {
                        g.FillRectangle(Brushes.White, 0, 0, scaledIconWidth, scaledIconHeight);
                        var bi = Program.BattleIconManager.GetBattleIcon(battle.BattleID);
                        g.DrawImageUnscaled(bi.Image, 0, 0);
                    }
                    gameBox.Invalidate();

                    RefreshTooltip();


                    var team = battle.GetFreeTeamID(client.UserName);

                    client.ChangeMyBattleStatus(desiredSpectatorState, HasAllResources() ? SyncStatuses.Synced : SyncStatuses.Unsynced, 0, team);
                };


            client.MyBattleMapChanged += (s, e) =>
                {
                    if (client.MyBattle != null && !Program.SpringScanner.HasResource(client.MyBattle.MapName))
                    {
                        client.ChangeMyBattleStatus(syncStatus: SyncStatuses.Unsynced);
                        Program.Downloader.GetResource(DownloadType.MAP, client.MyBattle.MapName);
                    }
                    RefreshTooltip();
                };

            client.MyBattleHostExited += (s, e) => { barContainer.btnDetail.Text = "Start"; };

            client.MyBattleStarted += (s, e) =>
                {
                    try
                    {
                        barContainer.btnDetail.Text = "Rejoin";
                        if (client.MyBattleStatus.SyncStatus == SyncStatuses.Synced)
                        {
                            if (Utils.VerifySpringInstalled())
                            {
                                if (spring.IsRunning) spring.ExitGame();
                                lastScript = spring.ConnectGame(client.MyBattle.Ip, client.MyBattle.HostPort, client.UserName,
                                    client.MyBattle.Users[client.UserName].ScriptPassword); //use MT tag when in spectator slot
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error starting spring: " + ex.Message);
                    }
                    RefreshTooltip();
                };

            client.BattleMyUserStatusChanged += (s, e) =>
                {
                    if (client.MyBattleStatus != null)
                    {
                        barContainer.btnDetail.Enabled = client.MyBattleStatus.SyncStatus == SyncStatuses.Synced;

                        if (client.MyBattleStatus.IsSpectator && radioPlay.Checked) ChangeGuiSpectatorWithoutEvent(false); // i was spectated
                        if (!client.MyBattleStatus.IsSpectator && radioSpec.Checked) ChangeGuiSpectatorWithoutEvent(true); //i was unspectated
                    }
                };

            client.BattleClosed += (s, e) =>
                {
                    barContainer.btnDetail.Text = "Start";
                    if (gameBox.Image != null) gameBox.Image.Dispose();
                    gameBox.Image = null;
                    RefreshTooltip();
                    Stop();
                };

            client.MyBattleRemoved += (s, e) =>
                {
                    var t = new Timer();
                    var tryCount = 0;
                    t.Interval = 1000;
                    t.Tick += (s2, e2) =>
                        {
                            tryCount++;
                            if (tryCount > 15)
                            {
                                t.Stop();
                                t.Dispose();
                            }
                            else if (client.IsLoggedIn && client.MyBattle == null)
                            {
                                var bat = client.ExistingBattles.Values.FirstOrDefault(x => x.Founder.Name == lastBattleFounder && !x.IsPassworded);
                                if (bat != null)
                                {
                                    ActionHandler.JoinBattle(bat.BattleID, null);
                                    t.Stop();
                                    t.Dispose();
                                }
                            }
                        };
                    t.Start();
                };

            client.ConnectionLost += (s, e) =>
                {
                    if (gameBox.Image != null) gameBox.Image.Dispose();
                    gameBox.Image = null;
                    RefreshTooltip();
                    Stop();
                };


            // process special queue message to display in label
            client.Said += (s, e) =>
            {
                if (e.Place == SayPlace.Battle && client.MyBattle != null && client.MyBattle.Founder.Name == e.UserName && e.Text.StartsWith("Queue"))
                {
                    var t = e.Text.Substring(6);
                    queueLabelFormatter = Regex.Replace(t,
                        "([0-9]+)s",
                        m =>
                        {
                            var queueSeconds = int.Parse(m.Groups[1].Value);
                            queueTarget = DateTime.Now.AddSeconds(queueSeconds);
                            return "{0}s";
                        });
                    lbQueue.Text = string.Format(queueLabelFormatter, Math.Round(queueTarget.Subtract(DateTime.Now).TotalSeconds));
                }
            };


            timer.Tick += (s, e) =>
                {
                    if (client.IsLoggedIn)
                    {
                        if (WindowsApi.IdleTime.TotalMinutes > Program.Conf.IdleTime) {
                            if (!client.MyUser.IsAway) client.ChangeMyUserStatus(isAway: true);
                        } else {
                            if (client.MyUser.IsAway) client.ChangeMyUserStatus(isAway: false);
                        }
                        CheckMyBattle();
                    }
                    if (client.MyBattle != null && client.MyBattle.IsQueue)
                    {
                        lbQueue.Text = string.Format(queueLabelFormatter, Math.Round(queueTarget.Subtract(DateTime.Now).TotalSeconds));
                    }
                };
            timer.Interval = 1000;
            timer.Start();

            Program.BattleIconManager.BattleChanged += BattleIconManager_BattleChanged;

            //picoChat.Font = new Font(Program.Conf.ChatFont.FontFamily, Program.Conf.ChatFont.Size*0.8f);
            picoChat.ShowHistory = false;
            picoChat.ShowJoinLeave = false;
            //picoChat.HideScroll = true;

            BattleChatControl.BattleLine += (s, e) => picoChat.AddLine(e.Data);

            picoChat.MouseClick += (s, e) => NavigationControl.Instance.Path = "chat/battle";
        }
コード例 #34
0
 public ProtocolExtension(TasClient tas, Action<string, Dictionary<string, string>> notifyUserExtensionChange) {
     this.tas = tas;
     this.notifyUserExtensionChange = notifyUserExtensionChange;
     tas.PreviewSaid += tas_PreviewSaid;
     //tas.LoginAccepted += (s, e) => tas.JoinChannel(ExtensionChannelName);
 }
コード例 #35
0
        public void RunNub(int num)
        {
            var tas = new TasClient("Nubotron");

            var maps = AutoRegistrator.RegistratorRes.campaignMaps.Split('\n');
            var name = "TestNub" + num;
            var ord  = num / 16;

            //tas.Input += (sender, args) => { Console.WriteLine(" < {0}", args); };
            //tas.Output += (sender, args) => { Console.WriteLine(" > {0}", args); };

            tas.Connected += (sender, args) =>
            {
                tas.Login(name, "dummy");
            };

            tas.ConnectionLost += (sender, args) => { tas.Connect(GlobalConst.LobbyServerHost, GlobalConst.LobbyServerPort); Console.WriteLine("disconnected"); };


            tas.LoginAccepted += (sender, args) => { Console.WriteLine(name + " accepted"); };
            tas.LoginDenied   += (sender, args) => { tas.Register(name, "dummy"); };

            tas.RegistrationAccepted += (sender, args) => { tas.Login(name, "dummy"); };
            tas.RegistrationDenied   += (sender, response) => { Console.WriteLine(name + "registration denied"); };



            tas.Connect(GlobalConst.LobbyServerHost, GlobalConst.LobbyServerPort);

            Task.Factory.StartNew(async() =>
            {
                while (true)
                {
                    await Task.Delay(rand.Next(10000));
                    if (tas.IsLoggedIn)
                    {
                        await tas.LeaveBattle();
                        if (tas.ExistingBattles.Count < 20)
                        {
                            await tas.OpenBattle(new BattleHeader()
                            {
                                Title      = "" + name,
                                MaxPlayers = 16,
                                Mode       = AutohostMode.None,
                                Engine     = tas.ServerWelcome.Engine,
                                Game       = tas.ServerWelcome.Game,
                                Map        = maps[rand.Next(maps.Length)],
                            });
                        }
                        else
                        {
                            var bats = tas.ExistingBattles.Values.ToList();
                            if (bats.Count > 0)
                            {
                                var bat = bats[rand.Next(bats.Count)];
                                if (bat != null)
                                {
                                    tas.JoinBattle(bat.BattleID);
                                }
                            }
                        }
                    }
                }
            }, TaskCreationOptions.LongRunning);


            Task.Factory.StartNew(async() =>
            {
                while (true)
                {
                    await Task.Delay(rand.Next(50000));
                    if (tas.IsLoggedIn)
                    {
                        tas.Say(SayPlace.Channel, "zk", sent.GetNext(), false);
                    }
                }
            }, TaskCreationOptions.LongRunning);

            Task.Factory.StartNew(async() =>
            {
                bool cycler = false;
                while (true)
                {
                    await Task.Delay(rand.Next(5000));
                    if (tas.IsLoggedIn)
                    {
                        await tas.ChangeMyUserStatus(cycler, cycler);
                        //await tas.ChangeMyBattleStatus(cycler, SyncStatuses.Synced, 1);
                        cycler = !cycler;
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }
コード例 #36
0
 static void TasClientInvoker(TasClient.Invoker a)
 {
     if (!CloseOnNext) MainWindow.InvokeFunc(() => a());
 }
コード例 #37
0
 public VoteMove(TasClient tas, Spring spring, AutoHost ah): base(tas, spring, ah) {}
コード例 #38
0
        public MatchMakerQueue(AutoHost ah)
        {
            this.ah = ah;
            ah.Commands.Commands.RemoveAll(x => !allowedCommands.Contains(x.Name));

            tas = ah.tas;

            tas.BattleOpened += (sender, args) =>
            {
                starting = false;
                UpdateCount();
                StopIfCountLow();
                lastCount = count;
            };

            tas.BattleUserJoined += (sender, args) =>
            {
                if (tas.MyBattleID != args.BattleID)
                {
                    return;
                }
                tas.Say(SayPlace.BattlePrivate,
                        args.UserName,
                        string.Format("Hi {0}, you are {1}. in the queue", args.UserName, tas.MyBattle.NonSpectatorCount),
                        true);
            };

            tas.BattleUserLeft += (sender, args) =>
            {
                if (tas.MyBattleID != args.BattleID)
                {
                    return;
                }

                UpdateCount();
                StopIfCountLow();
                lastCount = count;
            };

            tas.BattleUserStatusChanged += (sender, args) =>
            {
                UpdateCount();
                if (count != lastCount)                     // user count changed
                {
                    if (count > lastCount)                  // users added
                    {
                        if (count >= ah.config.MinToJuggle) // enough to start
                        {
                            if (!starting)                  // start fresh
                            {
                                startingFrom   = DateTime.Now;
                                scheduledStart = startingFrom.AddSeconds(initialDelay); // start in one minute
                                starting       = true;
                                foreach (var user in tas.MyBattle.Users.Keys)
                                {
                                    tas.Ring(SayPlace.BattlePrivate, user);
                                }
                            }
                            else // postpone
                            {
                                DateTime postpone = scheduledStart.AddSeconds(newJoinerDelay);
                                DateTime deadline = startingFrom.AddSeconds(maxDelay);
                                if (postpone > deadline)
                                {
                                    scheduledStart = deadline;
                                }
                                else
                                {
                                    scheduledStart = postpone;
                                }
                            }
                            tas.Say(SayPlace.Battle,
                                    "",
                                    string.Format("Queue starting in {0}s", Math.Round(scheduledStart.Subtract(DateTime.Now).TotalSeconds)),
                                    true);
                        }
                        else // not enough to start
                        {
                            tas.Say(SayPlace.Battle, "", string.Format("Queue needs {0} more people", ah.config.MinToJuggle - count), true);
                        }
                    }
                    else // users removed
                    {
                        StopIfCountLow();
                    }

                    lastCount = count;
                }
            };

            var timer = new Timer();

            timer.Interval  = 1000;
            timer.AutoReset = true;
            timer.Elapsed  += (sender, args) =>
            {
                if (starting && DateTime.Now >= scheduledStart)
                {
                    starting = false;

                    var teams = BuildTeams();
                    if (teams == null)
                    {
                        tas.Say(SayPlace.Battle, "", "Queue cannot start yet because of skill differences", true);
                    }
                    else
                    {
                        var spectators =
                            tas.MyBattle.Users.Values.Where(x => x.IsSpectator && x.Name != tas.MyBattle.Founder.Name && x.SyncStatus == SyncStatuses.Synced).ToList();

                        foreach (var t in teams)
                        {
                            CreateSlave(t, spectators);
                            spectators = null;
                        }
                    }
                }
            };

            timer.Start();
        }
コード例 #39
0
 public VoteKick(TasClient tas, Spring spring, AutoHost ah) : base(tas, spring, ah)
 {
 }
コード例 #40
0
 private void Event_Startbutton_Click(object sender, EventArgs e)
 {
     if (map_comboBox.SelectedItem == null || engine_comboBox.SelectedItem == null || game_comboBox.SelectedItem == null)
         Set_InfoLabel();
     else
     {
         var script = currentMod.IsMission ? currentMod.MissionScript : Get_Startscript();
         if (spring.IsRunning) spring.ExitGame();
         TasClient client = new TasClient("SkirmishTab", null, "127.0.0.1");
         spring.SpringExited += Event_SpringExited;
         infoLabel.Text = "Spring starting ...";
         spring.StartGame(client, null, null, script, Program.Conf.UseSafeMode);
     }
 }
コード例 #41
0
 public PlayerMover(TasClient tas)
 {
     this.tas  = tas;
     tas.Said += tas_Said;
 }
コード例 #42
0
 public VoteSetOptions(TasClient tas, Spring spring, AutoHost ah): base(tas, spring, ah) {}
コード例 #43
0
        public ZklSteamHandler(TasClient tas)
        {
            this.tas = tas;
            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                if (Environment.Is64BitProcess)
                {
                    EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.libCSteamworks-x86_64.so", "libCSteamworks.so");
                    EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.libsteam_api-x86_64.so", "libsteam_api.so");
                }
                else
                {
                    EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.libCSteamworks.so", "libCSteamworks.so");
                    EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.libsteam_api.so", "libsteam_api.so");
                }
            }
            else
            {
                EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.CSteamworks.dll", "CSteamworks.dll");
                EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.steam_api.dll", "steam_api.dll");
            }
            EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.steam_appid.txt", "steam_appid.txt");

            SteamHelper              = new SteamClientHelper();
            SteamHelper.SteamOnline += () =>
            {
                SteamName = SteamHelper.GetMyName();
                friends   = SteamHelper.GetFriends();
                SteamID   = SteamHelper.GetSteamID();
                if (tas.IsLoggedIn && tas.MyUser != null && tas.MyUser.EffectiveElo != 0)
                {
                    OnLoggedToBothSteamAndTas();
                }
            };


            tas.MyUserStatusChanged += (sender, args) => { if (SteamHelper.IsOnline && SteamID != 0)
                                                           {
                                                               OnLoggedToBothSteamAndTas();
                                                           }
            };
            tas.UserStatusChanged += (sender, args) =>
            {
                if (args.New.SteamID != null && args.Old.SteamID != args.New.SteamID && args.New.SteamID != 0)
                {
                    Voice.AddListenerSteamID(args.New.SteamID.Value); // todo only for battle in future
                    if (friends.Contains(args.New.SteamID.Value))
                    {
                        AddFriend(args.New.Name);
                    }
                }
            };

            tas.UserRemoved += (sender, args) =>
            {
                User us;
                if (tas.ExistingUsers.TryGetValue(args.Name, out us) && us.SteamID.HasValue)
                {
                    Voice.RemoveListenerSteamID(us.SteamID.Value);
                }
            };
        }
コード例 #44
0
        public void RunNub(int num)
        {
            var tas     = new TasClient("Nubotron");
            var name    = "TestNub" + num;
            var ord     = num / 16;
            var batname = "Test " + ord;

            //tas.Input += (sender, args) => { Console.WriteLine(" < {0}", args); };
            //tas.Output += (sender, args) => { Console.WriteLine(" > {0}", args); };

            tas.Connected += (sender, args) => {
                tas.Login(name, "dummy");
            };

            tas.ConnectionLost += (sender, args) => { tas.Connect(GlobalConst.LobbyServerHost, GlobalConst.LobbyServerPort); Console.WriteLine("disconnected"); };


            tas.LoginAccepted += (sender, args) => { Console.WriteLine(name + " accepted"); };
            tas.LoginDenied   += (sender, args) => { tas.Register(name, "dummy"); };

            tas.RegistrationAccepted += (sender, args) => { tas.Login(name, "dummy"); };
            tas.RegistrationDenied   += (sender, response) => { Console.WriteLine(name + "registration denied"); };



            tas.UserAdded += (sender, args) => {
                if (args.Name == name)
                {
                    tas.JoinChannel("bots");
                    if (num % 16 == 0)
                    {
                        tas.OpenBattle(new BattleHeader()
                        {
                            Title      = batname,
                            MaxPlayers = 16,
                        });
                    }
                    else
                    {
                        var bat = tas.ExistingBattles.Values.FirstOrDefault(x => x.Title == batname);
                        if (bat != null)
                        {
                            tas.JoinBattle(bat.BattleID);
                        }
                    }
                }
            };
            tas.BattleFound += (sender, args) => {
                if (args.Title == batname)
                {
                    //await Task.Delay(200);
                    tas.JoinBattle(args.BattleID);
                }
            };


            tas.Connect(GlobalConst.LobbyServerHost, GlobalConst.LobbyServerPort);

            /*Task.Factory.StartNew(async () =>
             * {
             *  while (true)
             *  {
             *      await Task.Delay(rand.Next(400000));
             *      tas.Say(SayPlace.Channel, "zk", sent.GetNext(), false);
             *  }
             * }, TaskCreationOptions.LongRunning);*/
        }
コード例 #45
0
        public static void Main(string[] args)
        {
            try
            {
                GlobalConst.Mode =ModeType.Live;
                //Stopwatch stopWatch = new Stopwatch(); stopWatch.Start();

                Trace.Listeners.Add(new ConsoleTraceListener());
                Trace.Listeners.Add(new LogTraceListener());

                if (Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    var ver = GetNetVersionFromRegistry();
                    if (ver < 378675)
                    {
                        MessageBox.Show("Zero-K launcher needs Microsoft .NET framework 4.5.1\nPlease download and install it first",
                            "Program is unable to run", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }


                Directory.SetCurrentDirectory(StartupPath);

                SelfUpdater = new SelfUpdater("Zero-K");

                // if (Process.GetProcesses().Any(x => x.ProcessName.StartsWith("spring_"))) return; // dont start if started from installer
                StartupArgs = args;


                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!Debugger.IsAttached)
                {
                    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                    Thread.GetDomain().UnhandledException += UnhandledException;
                    Application.ThreadException += Application_ThreadException;
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                }

                //HttpWebRequest.DefaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);



                Trace.TraceInformation("Starting with version {0}", SelfUpdater.CurrentVersion);

                WebRequest.DefaultWebProxy = null;
                ThreadPool.SetMaxThreads(500, 2000);
                ServicePointManager.Expect100Continue = false;

                LoadConfig();


                var contentDir = !string.IsNullOrEmpty(Conf.DataFolder) ? Conf.DataFolder : StartupPath;
                if (!Directory.Exists(contentDir) || !SpringPaths.IsDirectoryWritable(contentDir) || pickInitFolder || contentDir.Contains("Local\\Apps"))
                {
                    var dc = new SelectWritableFolder() { SelectedPath = SpringPaths.GetMySpringDocPath() };
                    if (dc.ShowDialog() != DialogResult.OK) return;
                    contentDir = dc.SelectedPath;
                }
                if (Conf.DataFolder != StartupPath) Conf.DataFolder = contentDir;
                else Conf.DataFolder = null;

                if (!SpringPaths.IsDirectoryWritable(StartupPath) || StartupPath.Contains("Local\\Apps"))
                {
                    MessageBox.Show(
                        string.Format(
                            "Please use the newly created desktop icon to start Zero-K not this one.\r\nZero-K.exe will be moved to {0}",
                            contentDir), "Startup directory is not writable!");
                    var newTarget = Path.Combine(contentDir, "Zero-K.exe");
                    if (SelfUpdater.CheckForUpdate(newTarget, true))
                    {
                        Conf.Save(Path.Combine(contentDir, Config.ConfigFileName));
                        Process.Start(newTarget);
                        return;
                    }
                    MessageBox.Show("Move failed, please copy Zero-K.exe to a writable folder");
                }




                SpringPaths = new SpringPaths(null, writableFolderOverride: contentDir);
                SpringPaths.MakeFolders();
                SpringPaths.SetEnginePath(Utils.MakePath(SpringPaths.WritableDirectory, "engine", ZkData.GlobalConst.DefaultEngineOverride ?? TasClient.ServerSpringVersion));

                // run unitsync as soon as possible so we don't have to spend several minutes doing it on game start
                // two problems:
                // 1) unitsync can only be loaded once, even if in a different directory http://msdn.microsoft.com/en-us/library/ms682586.aspx#factors_that_affect_searching
                //  so if we do it in SpringVersionChanged it'll be done at startup for GlobalConst.DefaultEngineOverride, then for no other engine version
                // 2) unitsync can't be unloaded http://stackoverflow.com/questions/1371877/how-to-unload-the-dll-using-c
                // also see EngineDownload.cs
                //SpringPaths.SpringVersionChanged += (s, e) =>
                //{
                //    //System.Diagnostics.Trace.TraceInformation("SpringPaths version: {0}", SpringPaths.SpringVersion);
                //    //new PlasmaShared.UnitSyncLib.UnitSync(SpringPaths);
                //    //SpringScanner.VerifyUnitSync();
                //    //if (SpringScanner != null) SpringScanner.Dispose();
                //    //SpringScanner = new SpringScanner(SpringPaths);
                //    //SpringScanner.Start();
                //};

                SaveConfig();
                if (Conf.CleanCache)
                {
                    try
                    {
                        var path = Program.SpringPaths.WritableDirectory;
                        bool backupChatlogs = false;
                        string sdPath = Utils.MakePath(path, "cache", "SD");
                        string chatHistoryPath = Utils.MakePath(sdPath, "ChatHistory");
                        string backupPath = Utils.MakePath(path, "_chatlogBackup");
                        // save chatlogs and such
                        if (Directory.Exists(chatHistoryPath))
                        {
                            if (Directory.Exists(backupPath))
                                Directory.Delete(backupPath, true);
                            Directory.Move(chatHistoryPath, backupPath);
                            backupChatlogs = true;
                        }
                        Directory.Delete(Utils.MakePath(path, "cache"), true);
                        if (backupChatlogs)
                        {
                            if (!Directory.Exists(sdPath))
                                Directory.CreateDirectory(sdPath);
                            Directory.Move(backupPath, chatHistoryPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(ex.ToString());
                    }
                    finally
                    {
                        Conf.CleanCache = false;
                        SaveConfig();
                    }
                }

                try
                {
                    if (!Debugger.IsAttached)
                    {
                        var wp = "";
                        foreach (var c in SpringPaths.WritableDirectory.Where(x => (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'))) wp += c;
                        mutex = new Mutex(false, "ZeroKLobby" + wp);
                        if (!mutex.WaitOne(10000, false))
                        {
                            MessageBox.Show(
                                "Another copy of Zero-K launcher is still running" +
                                "\nMake sure the other launcher is closed (check task manager) before starting new one",
                                "There can be only one launcher running",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Stop);
                            return;
                        }
                    }
                }
                catch (AbandonedMutexException) { }

                if (Conf.IsFirstRun)
                {
                    DialogResult result = MessageBox.Show("Create a desktop icon for Zero-K?", "Zero-K", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes) 
                    {
                        Utils.CreateDesktopShortcut();
                    }
                }

                FriendManager = new FriendManager();
                AutoJoinManager = new AutoJoinManager();
                EngineConfigurator = new EngineConfigurator(SpringPaths.WritableDirectory);

                SpringScanner = new SpringScanner(SpringPaths);
                SpringScanner.LocalResourceAdded += (s, e) => Trace.TraceInformation("New resource found: {0}", e.Item.InternalName);
                SpringScanner.LocalResourceRemoved += (s, e) => Trace.TraceInformation("Resource removed: {0}", e.Item.InternalName);
                if (Program.Conf.EnableUnitSyncPrompt && Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    SpringScanner.UploadUnitsyncData += MicroForms.UnitSyncUploadPrompt.SpringScanner_UploadUnitsyncData;
                    SpringScanner.RetryResourceCheck += MicroForms.UnitSyncRetryPrompt.SpringScanner_RetryGetResourceInfo;
                }

                SpringScanner.MapRegistered += (s, e) => Trace.TraceInformation("Map registered: {0}", e.MapName);
                SpringScanner.ModRegistered += (s, e) => Trace.TraceInformation("Mod registered: {0}", e.Data.Name);

                Downloader = new PlasmaDownloader.PlasmaDownloader(Conf, SpringScanner, SpringPaths); //rapid
                Downloader.DownloadAdded += (s, e) => Trace.TraceInformation("Download started: {0}", e.Data.Name);

                var isLinux = Environment.OSVersion.Platform == PlatformID.Unix;
                TasClient = new TasClient(string.Format("ZK {0}{1}", SelfUpdater.CurrentVersion, isLinux ? " linux" : ""));

                SayCommandHandler = new SayCommandHandler(TasClient);

                ServerImages = new ServerImagesHandler(SpringPaths, TasClient);


                // log, for debugging
                TasClient.Connected += (s, e) => Trace.TraceInformation("TASC connected");
                TasClient.LoginAccepted += (s, e) => {
                    Trace.TraceInformation("TASC login accepted");
                    Trace.TraceInformation("Server is using Spring version {0}", TasClient.ServerSpringVersion);
                };

                TasClient.LoginDenied += (s, e) => Trace.TraceInformation("TASC login denied");
                TasClient.ChannelJoined += (s, e) => { Trace.TraceInformation("TASC channel joined: " + e.Name); };
                TasClient.ConnectionLost += (s, e) => Trace.TraceInformation("Connection lost");

                // special handling
                TasClient.PreviewSaid += (s, e) =>
                {
                    var tas = (TasClient)s;
                    User user = null;
                    if (e.Data.UserName != null)
                    {
                        tas.ExistingUsers.TryGetValue(e.Data.UserName, out user);
                        if ((user != null && user.BanMute) || Conf.IgnoredUsers.Contains(e.Data.UserName)) e.Cancel = true;
                    }
                };

                TasClient.Extensions.JsonDataReceived += (eventArgs, o) =>
                    {
                        var command = o as ProtocolExtension.SiteToLobbyCommand;
                        if (command != null)
                        {
                            MainWindow.navigationControl.Path = command.SpringLink;
                            MainWindow.PopupSelf();
                        }
                    };

                ModStore = new ModStore();
                ToolTip = new ToolTipHandler();
                BrowserInterop = new BrowserInterop();
                BattleIconManager = new BattleIconManager();

                Application.AddMessageFilter(ToolTip);


                SteamHandler = new ZklSteamHandler(TasClient);
                SteamHandler.Connect();


                MainWindow = new MainWindow();

                Application.AddMessageFilter(new ScrollMessageFilter());

                BattleBar = new BattleBar();
                NewVersionBar = new NewVersionBar(SelfUpdater);
                VoteBar = new VoteBar();
                PwBar = new PwBar();

                if (!Debugger.IsAttached && !Conf.DisableAutoUpdate) Program.SelfUpdater.StartChecking();

                Application.Run(MainWindow);
                ShutDown();
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleException(ex, true);
            }
            finally
            {
                ShutDown();
            }
            if (ErrorHandling.HasFatalException && !Program.CloseOnNext) Application.Restart();
        }
コード例 #46
0
        public static void ProcessResult(RecognitionResult result, SpeechSynthesizer speechSynthesizer, TasClient client)
        {
            var grammar = zkGrammars.FirstOrDefault(g => result.Grammar.Name == g.Name);

            if (grammar == null)
            {
                speechSynthesizer.SpeakAsync("What was that?");
            }
            grammar.Aknowledge(speechSynthesizer, result);
            var table = grammar.ToLua(result);

            client.Say(TasClient.SayPlace.User, client.MyBattle.Founder.Name, "!transmit voice" + table.Replace("\n", ""), false);
        }
コード例 #47
0
 public VoteSetOptions(TasClient tas, Spring spring, AutoHost ah) : base(tas, spring, ah)
 {
 }