示例#1
0
        public void Start(EndPoint ep)
        {
            _socket         = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.NoDelay = NoDelayAlgorithm;
            _socket.Bind(ep);
            _socket.Listen(MaximumPendingConnections);

            _log.Info("Socket bound to {0}.", ep);

            // Start accepting incoming connections.
            Accept(null);
        }
示例#2
0
        private AccountManager()
        {
            _log.Info("Loading accounts...");

            var accounts = AccountApplication.Instance.AccountDbContext.FindAll <AccountRecord>();

            foreach (var acc in accounts.Select(account => new Account(account)))
            {
                Contract.Assume(acc != null);
                AddAccount(acc);
            }

            _log.Info("Loaded {0} accounts.", _accounts.Count);
        }
示例#3
0
文件: Start.cs 项目: winal/Scree
 protected override void OnStart(string[] args)
 {
     LogProxy.Info("同步服务端启动开始");
     Scree.Core.IoC.ServiceRoot.Init();
     LogProxy.Info("同步服务端启动结束");
     // TODO: 在此处添加代码以启动服务。
 }
示例#4
0
 private static void Log(string message)
 {
     if (DebugLog)
     {
         LogProxy.Info(message);
     }
 }
示例#5
0
        public void Start(string[] args)
        {
            Contract.Requires(args != null);

            GC.Collect();

            var asmPath = Assembly.GetEntryAssembly().Location;

            Contract.Assume(!string.IsNullOrEmpty(asmPath));
            _configuration = new ApplicationConfiguration(asmPath);
            _configuration.ScanAll();
            _configuration.Open();

            InitializationManager.InitializeAll();

            try
            {
                OnStart(args);
            }
            catch (Exception ex)
            {
                ExceptionManager.RegisterException(ex);
            }

            _log.Info("{0} initialized.", GetType().Name);
        }
示例#6
0
 public void Start()
 {
     if (Application.isEditor)
     {
         LogProxy.Info("Ading callback for editor state change");
         EditorApplication.playmodeStateChanged += PlaymodeStateChanged;
     }
 }
示例#7
0
        protected override void OnTerminate()
        {
            LogProxy.Info("PlayingState: OnTerminate");


            _photonClient.CurrentRoom.Messenger.Unsubscribe((int)ITAlertChannel.SimulationState, ProcessSimulationStateMessage);

            base.OnTerminate();
        }
示例#8
0
        /// <summary>
        /// Initialize the object from simulation state
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="director"></param>
        public void Initialize(Entity entity, Director director)
        {
            Entity   = entity;
            Director = director;
            Entity.TryGetComponent(out _tutorialHighlight);
            OnInitialize();
            Initialized = true;

            LogProxy.Info($"EntityBehviour Initialize: GameObject {gameObject.name} Entity {Entity?.Id.ToString() ?? "null"} Director {Director?.InstanceId ?? "null"}");
        }
示例#9
0
        protected override void OnInitialize()
        {
            LogProxy.Info("PlayingState: OnInitialize");

            _photonClient.CurrentRoom.Messenger.Subscribe((int)ITAlertChannel.SimulationState, ProcessSimulationStateMessage);

            IsComplete = false;

            base.OnInitialize();
        }
示例#10
0
        protected override void OnEnter()
        {
            Logger.LogDebug("Entered " + StateName);

            LogProxy.Info("PlayingState: OnEnter");
            _photonClient.CurrentRoom.Messenger.SendMessage(new PlayingMessage
            {
                PlayerPhotonId = _photonClient.CurrentRoom.Player.PhotonId
            });
        }
示例#11
0
        protected override void OnEnter()
        {
            Logger.LogDebug("Entered " + StateName);
            LogProxy.Info("InitializingState OnEnter");

            _photonClient.CurrentRoom.Messenger.Subscribe((int)ITAlertChannel.SimulationState, ProcessSimulationStateMessage);
            _photonClient.CurrentRoom.Messenger.SendMessage(new InitializingMessage
            {
                PlayerPhotonId = _photonClient.CurrentRoom.Player.PhotonId
            });
            PlayGen.Unity.Utilities.Loading.Loading.Start();
        }
示例#12
0
        public void ResetDirector()
        {
            LogProxy.Info("Director: ResetDirector");

            if (SimulationRoot != null)
            {
                SimulationRoot.ECS.EntityRegistry.EntityDestroyed -= EntityRegistryOnEntityDestroyed;
            }

            _messageSignal.Reset();
            _updateSignal.Reset();
            _updateCompleteSignal.Reset();
            _terminateSignal.Reset();

            ThreadWorkerException = null;

            Player = null;
            if (_trackedEntities == null)
            {
                _trackedEntities = new Dictionary <int, UIEntity>(DefaultntityCapacity);
            }
            foreach (var entity in _trackedEntities)
            {
                entity.Value.EntityBehaviour.ResetEntity();
                Destroy(entity.Value.GameObject);
            }
            _trackedEntities.Clear();

            if (_untrackedEntities == null)
            {
                _untrackedEntities = new List <UIEntity>(DefaultntityCapacity);
            }
            foreach (var entity in _untrackedEntities)
            {
                entity.EntityBehaviour.ResetEntity();
                Destroy(entity.GameObject);
            }
            _untrackedEntities.Clear();

            lock (_destroyedEntityLock)
            {
                if (_destroyedEntities == null)
                {
                    _destroyedEntities = new List <int>(DefaultntityCapacity);
                }
                _destroyedEntities.Clear();
            }

            OnReset();

            LogProxy.Info($"_trackedEntities: {_trackedEntities.Count}, UntrackedEntities: {_untrackedEntities.Count}");
        }
示例#13
0
        protected override void OnExit()
        {
            LogProxy.Info("RoomState: OnExit");

            _director.StopWorker();
            _director.ResetDirector();

            _photonClient.CurrentRoom?.Leave();

            // CurrentRoom and messenger would have been destroyed by this point so no need to unsubscribe
            _stateController.Terminate();

            PlayGen.Unity.Utilities.Loading.Loading.Stop();
        }
        private static void RunInitializable(IEnumerable<InitializationInfo> list, InitializationInfo init, bool value)
        {
            Contract.Requires(list != null);
            Contract.Requires(init != null);

            // Prevent duplicate initialization/teardown.
            if (init.Initialized == value)
                return;

            var attr = init.Attribute;
            var type = init.Method.DeclaringType;
            var depType = attr.Dependency;

            if (value && depType != null)
            {
                var dep = list.FirstOrDefault(x => x.Method.DeclaringType == depType);

                if (dep != null)
                    if (!dep.Initialized)
                        RunInitializable(list, dep, true);
            }

            if (!value)
            {
                var dep = list.FirstOrDefault(x => x.Attribute.Dependency == type);

                if (dep != null)
                    if (dep.Initialized)
                        RunInitializable(list, dep, false);
            }

            var initType = value ? "initialization" : "teardown";

            try
            {
                init.Method.Invoke(null, new object[] { value });
                init.Initialized = value;

                _log.Info("Completed {0} of {1} successfully.", initType, type.Name);
            }
            catch (TargetInvocationException e)
            {
                var ex = e.InnerException;

                _log.Error("Error in {0} of {1}:", initType, init.Attribute.Name);
                _log.Error("{0}", ex.Message);
                _log.Error("{0}", ex.StackTrace);
            }
        }
示例#15
0
        private void OnApplicationQuit()
        {
            if (!_isDisposed)
            {
                Application.CancelQuit();

                _stateController.Terminate();
                LogProxy.Info("Game Quit Gracefully.");
                Logger.Flush();

                _isDisposed = true;

                Application.Quit();
            }
        }
        protected override void OnEnter()
        {
            Logger.LogDebug("Entered " + StateName);
            LogProxy.Info("LaunchQuestionnaireState OnEnter");

            // The following string contains the key for the google form is used for the cognitive load questionnaire
            var formsKey = "1FAIpQLSctM-kR-1hlmF6Nk-pQNIWYnFGxRAVvyP6o3ZV0kr8K7JD5dQ";

            // Google form ID
            var googleFormsURL = "https://docs.google.com/forms/d/e/"
                                 + formsKey
                                 + "/viewform?entry.1596836094="
                                 + SUGARManager.CurrentUser.Name;

            // Open the default browser and show the form
            UnityEngine.Application.OpenURL(googleFormsURL);
            UnityEngine.Application.Quit();
        }
示例#17
0
        private static void ServicesInit()
        {
            int fails = 0;

            while (true)
            {
                int lastFails = fails;
                fails = 0;

                bool isInitialized = true;
                foreach (var v in Services.Values)
                {
                    if (v.IsInitialized)
                    {
                        continue;
                    }

                    LogProxy.Info(string.Format(SERVICEBEGININIT, v.ToString()));

                    ((ServiceBase)v).IsInitialized = v.Init();

                    if (v.IsInitialized)
                    {
                        LogProxy.Info(string.Format(SERVICEENDINIT, v.ToString()));
                    }
                    else
                    {
                        LogProxy.Info(string.Format(SERVICEINITFAIL, v.ToString()));
                        fails++;
                        isInitialized = false;
                    }
                }

                if (isInitialized)
                {
                    return;
                }

                if (lastFails <= fails)
                {
                    LogProxy.Fatal(SERVICESINITERROR, true);
                }
            }
        }
示例#18
0
 public void DisplayMap()
 {
     for (int i = 0; i < this._map.GetHeight(); i++)
     {
         string row = "";
         for (int j = 0; j < this._map.GetWidth(); j++)
         {
             if (this.TileIsPassable(i, j))
             {
                 row += "#";
             }
             else
             {
                 row += " ";
             }
         }
         LogProxy.Info(row);
     }
 }
示例#19
0
        private void SetupPlayers(List <ITAlertPlayer> players, int playerServerId)
        {
            LogProxy.Info("Director: Setup Players");
            foreach (var player in players)
            {
                try
                {
                    LogProxy.Info($"Director: Setup Players: Player {player.PhotonId}");

                    var internalPlayer = SimulationRoot.Configuration.PlayerConfiguration.Single(pc => pc.ExternalId == player.PhotonId);

                    if (_trackedEntities.TryGetValue(internalPlayer.EntityId, out var playerUiEntity))
                    {
                        var playerBehaviour = (PlayerBehaviour)playerUiEntity.EntityBehaviour;
                        playerBehaviour.PhotonId = player.PhotonId;
                        if (player.PhotonId == playerServerId)
                        {
                            LogProxy.Info($"Selected active player with id {playerServerId}: entity {playerBehaviour.Entity.Id}");
                            Player = playerBehaviour;
                            playerUiEntity.GameObject.GetComponent <Canvas>().sortingLayerName        = UIConstants.ActivePlayerSortingLayer;
                            playerUiEntity.GameObject.GetComponent <TrailRenderer>().sortingLayerName = UIConstants.ActivePlayerSortingLayer;
                            if (player.ExternalId.HasValue)
                            {
                                playerBehaviour.ExternalId = player.ExternalId.Value;
                            }
                        }
                    }
                    else
                    {
                        LogProxy.Warning($"No player entity with id: {internalPlayer.EntityId}");
                    }
                }
                catch (Exception ex)
                {
                    throw new SimulationIntegrationException($"Error mapping photon player '{playerServerId}' to simulation", ex);
                }
            }
            if (Player == null)
            {
                throw new SimulationIntegrationException($"Error mapping actiove photon player '{playerServerId}'");
            }
        }
示例#20
0
        protected override void OnEnter()
        {
            LogProxy.Info("RoomState: OnEnter");

            _photonClient.CurrentRoom.Messenger.Subscribe((int)ITAlertChannel.Error, ProcessErrorMessage);

            _voiceController = new VoiceController(
                _photonClient,
                _director,
                () => Input.GetKeyDown(KeyCode.Tab) || _talkButton.IsDownFrame,
                () => Input.GetKeyUp(KeyCode.Tab) || _talkButton.IsUpFrame || !Application.isFocused);

            _stateController = _controllerFactory.Create();
            _stateController.Initialize();

            if (!GameExceptionHandler.HasException)
            {
                _stateController.EnterState(LobbyState.StateName);
            }
        }
示例#21
0
 private void SugarLogin()
 {
     if (!IsComplete)
     {
         SUGARManager.Account.DisplayPanel(success =>
         {
             if (!success)
             {
                 if (!SUGARManager.Account.IsActive)
                 {
                     SugarLogin();
                 }
                 else
                 {
                     LogProxy.Info("Sugar Login Failed");
                 }
             }
         });
     }
 }
示例#22
0
        protected override void OnInitialize()
        {
            _antivirus            = null;
            _capture              = null;
            _timedActivation      = null;
            _consumableActivation = null;

            if (Entity.TryGetComponent(out _itemType) &&
                Entity.TryGetComponent(out _currentLocation) &&
                Entity.TryGetComponent(out _owner) &&
                Entity.TryGetComponent(out _activation))
            {
                _selectionOptions.SetActive(false);
                var spriteName = _itemType.GetType().Name.ToLowerInvariant();
                _descriptionText.GetComponent <TextLocalization>().Key = spriteName.ToUpperInvariant() + "_DESCRIPTION";
                LogProxy.Info($"Creating item type: {spriteName}");
                gameObject.name          = $"{Name}_{spriteName}";
                _foregroundSprite.sprite = Resources.Load <Sprite>(spriteName);
                _foregroundText.text     = string.Empty;

                Entity.TryGetComponent(out _timedActivation);
                Entity.TryGetComponent(out _antivirus);
                Entity.TryGetComponent(out _capture);
                Entity.TryGetComponent(out _consumableActivation);

                UpdateColour();

                _midgroundSprite.enabled = false;
                _midgroundSprite.type    = Image.Type.Simple;

                //TODO: extract item specific logic to subclasses
                InitializeAntivirus();
                InitializeCapture();
                UpdateInventory();
            }
            else
            {
                throw new EntityInitializationException($"Could not load all required components for Entity Id {Entity.Id}");
            }
        }
示例#23
0
        private static void ServicesLoad()
        {
            XElement root = XElement.Load(ConfigDirectory);
            IEnumerable <XElement> services = root.Elements("Service");

            string dllDir = Tools.GetAssemblyPath();

            Assembly driverAssembly, typeAssembly;
            Type     typeType, driverType;
            IService obj;

            foreach (var service in services)
            {
                string[] type   = service.Attribute("type").Value.Split(',');
                string[] driver = service.Attribute("driver").Value.Split(',');

                driverAssembly = Assembly.LoadFrom(string.Format("{0}{1}.dll", dllDir, driver[1].Trim(), ".dll"));
                typeAssembly   = Assembly.LoadFrom(string.Format("{0}{1}.dll", dllDir, type[1].Trim(), ".dll"));

                typeType   = typeAssembly.GetType(type[0].Trim());
                driverType = driverAssembly.GetType(driver[0].Trim());

                if (typeType == null || driverType == null)
                {
                    LogProxy.Fatal(string.Format(SERVICELOADFAIL, driver[0].Trim()), true);
                }

                obj = Activator.CreateInstance(driverType) as IService;

                if (obj == null)
                {
                    LogProxy.Fatal(string.Format(SERVICELOADFAIL, driver[0].Trim()), true);
                }

                LogProxy.Info(string.Format(SERVICELOADED, driver[0].Trim()));

                AddService(typeType, obj);
            }
        }
示例#24
0
        private void ProcessSimulationStateMessage(Message message)
        {
            if (message is ITAlert.Photon.Messages.Simulation.States.InitializedMessage initializedMessage)
            {
                LogProxy.Info("InitializingState: Received InitializedMessage");

                if (string.IsNullOrEmpty(initializedMessage.PlayerConfiguration) ||
                    string.IsNullOrEmpty(initializedMessage.ScenarioName) ||
                    _scenarioLoader.TryGetScenario(initializedMessage.ScenarioName, out var scenario) == false)
                {
                    throw new InvalidOperationException("Received invalid InitializedMessage.");
                }

                try
                {
                    scenario.Configuration.PlayerConfiguration = ConfigurationSerializer.Deserialize <List <PlayerConfig> >(initializedMessage.PlayerConfiguration);
                    // TODO: extract simulation initialization to somewhere else
                    var simulationRoot = SimulationInstaller.CreateSimulationRoot(scenario);
                    if (_director.Initialize(simulationRoot, _photonClient.CurrentRoom.Player.PhotonId, _photonClient.CurrentRoom.Players))
                    {
                        _photonClient.CurrentRoom.Messenger.SendMessage(new InitializedMessage
                        {
                            PlayerPhotonId = _photonClient.CurrentRoom.Player.PhotonId
                        });
                    }
                }
                catch (Exception ex)
                {
                    //TODO: transition back to lobby, or show error message

                    throw new SimulationException("Error creating simulation root", ex);
                }
            }
            else
            {
                throw new Exception("Unhandled Simulation State Message: " + message);
            }
        }
示例#25
0
        /// <summary>
        /// 预处理,启动内部服务,构筑运行环境,仅调用一次
        /// </summary>
        public static void Init()
        {
            if (InitStatus != InitStatus.None)
            {
                return;
            }

            lock (LockObj)
            {
                if (InitStatus != InitStatus.None)
                {
                    return;
                }

                InitStatus = InitStatus.Initing;
            }

            LogProxy.Info(SERVICESBEGININIT);

            try
            {
                ServicesLoad();

                ServicesInit();

                ServicesRun();
            }
            catch (Exception ex)
            {
                InitStatus = InitStatus.Fail;
                LogProxy.Fatal(ex, true);
            }

            InitStatus = InitStatus.Complete;

            LogProxy.Info(SERVICESENDINIT);
        }
示例#26
0
        private static void ServicesRun()
        {
            foreach (var v in Services.Values)
            {
                if (!v.IsInitialized)
                {
                    LogProxy.Fatal(string.Format(SERVICERUNFAILNOINIT, v.ToString()), true);
                    continue;
                }

                LogProxy.Info(string.Format(SERVICEBEGINRUN, v.ToString()));

                ((ServiceBase)v).IsRunned = v.Run();

                if (v.IsRunned)
                {
                    LogProxy.Info(string.Format(SERVICEENDRUN, v.ToString()));
                }
                else
                {
                    LogProxy.Fatal(string.Format(SERVICERUNFAIL, v.ToString()), true);
                }
            }
        }
示例#27
0
        private BanManager()
        {
            _log.Info("Loading account bans...");

            var accountBans = AccountApplication.Instance.AccountDbContext.FindAll <AccountBanRecord>();

            foreach (var accBan in accountBans.Select(accountBan => new AccountBan(accountBan)))
            {
                Contract.Assume(accBan != null);
                AddAccountBan(accBan);
            }

            _log.Info("Loaded {0} account bans.", _accountBans.Count);

            _log.Info("Loading IP bans...");

            var ipBans = AccountApplication.Instance.AccountDbContext.FindAll <IPBanRecord>();

            foreach (var ipBan in ipBans.Select(ipBan => new IPBan(ipBan)))
            {
                Contract.Assume(ipBan != null);
                AddIPBan(ipBan);
            }

            _log.Info("Loaded {0} IP bans.", _ipBans.Count);

            _log.Info("Loading IP range bans...");

            var ipRangeBans = AccountApplication.Instance.AccountDbContext.FindAll <IPRangeBanRecord>();

            foreach (var ipRangeBan in ipRangeBans.Select(ipRangeBan => new IPRangeBan(ipRangeBan)))
            {
                Contract.Assume(ipRangeBan != null);
                AddIPRangeBan(ipRangeBan);
            }

            _log.Info("Loaded {0} IP range bans.", _ipRangeBans.Count);
        }
示例#28
0
        /// <summary>
        /// Finds best possible tour through a set of points, traveling through all points.
        /// </summary>
        public void Compute()
        {
            this._ordered = new List <T>();

            if (this._items.Contains(this._start))
            {
                if (this._items.IndexOf(this._start) != 0)
                {
                    this._items.Remove(this._start);
                    this._items.Insert(0, this._start);
                }
            }
            else
            {
                this._items.Insert(0, this._start);
            }

            if (this._items.Count == 1)
            {
                this._ordered.Add(this._items[0]);
                return;
            }

            int[,] costMatrix = this.GenerateCostMatrix();
            int nodes = costMatrix.GetLength(0);

            for (int row = 0; row < nodes; row++)
            {
                string rowString = "";
                for (int col = 0; col < nodes; col++)
                {
                    rowString += costMatrix[row, col].ToString();
                    rowString += " ";
                }
                LogProxy.Info(rowString);
            }

            // Utilizing TSP greedy

            int counter = 0;
            int j       = 0;
            int i       = 0;
            int min     = int.MaxValue;

            List <int> visitedRouteList = new List <int>();

            visitedRouteList.Add(0);
            int[] route = new int[costMatrix.Length];

            while (i < costMatrix.GetLength(0) && j < costMatrix.GetLength(1))
            {
                if (counter >= costMatrix.GetLength(0) - 1)
                {
                    break;
                }

                if (j != i && !(visitedRouteList.Contains(j)))
                {
                    if (costMatrix[i, j] < min)
                    {
                        min            = costMatrix[i, j];
                        route[counter] = j + 1;
                    }
                }
                j++;

                if (j == costMatrix.GetLength(0))
                {
                    min = int.MaxValue;
                    visitedRouteList.Add(route[counter] - 1);

                    j = 0;
                    i = route[counter] - 1;
                    counter++;
                }
            }

            foreach (int index in visitedRouteList)
            {
                this._ordered.Add(this._items[index]);
            }
        }
示例#29
0
 private void OnEnable()
 {
     LogProxy.Info("Enabled");
 }
示例#30
0
 protected override void OnExit()
 {
     LogProxy.Info("PlayingState: OnExit");
 }