Esempio n. 1
0
 private void Start()
 {
     UnityThread.initUnityThread();
     ClientHandleData.InitializePackets();
     InitializeNetwork();
     //ClientTCP.InitializeNetworking();
 }
    void Awake()
    {
        /// Find all coins active in the scene.
        Coins = FindObjectsOfType <Coin>();

        Api = new BittrexWrapper("c18983bdefc341c3ac7b2b915b85f5ee", "8c9926193b7a46b5a440a9c74d9c6f5b");
        Api.Connect();

        _updateAction = (async() => {
            completedLastUpdate = false;

            var marketSummaries = await Task.Run(() => Api.GetMarketSummaries());

            var orderBooks = new Dictionary <string, OrderBook>();

            for (var i = 0; i < Coins.Length; i++)
            {
                var book = await Task.Run(() => Api.GetOrderBook(Coins[i].CoinName.Split('-')[0], Coins[i].CoinName.Split('-')[1]));
                orderBooks.Add(Coins[i].CoinName, book);
            }

            UnityThread.executeInUpdate(() => UpdatePrices(marketSummaries, orderBooks));

            completedLastUpdate = true;
        });

        Task.Run(_updateAction);
    }
 public void OnDisable()
 {
     if (instance == this)
     {
         instance = null;
     }
 }
Esempio n. 4
0
    private static void ReceiveCallback(IAsyncResult result)
    {
        try
        {
            int readBytes = myStream.EndRead(result);
            if (readBytes <= 0)
            {
                return;
            }

            byte[] newBytes = new byte[readBytes];
            Buffer.BlockCopy(receiveBuffer, 0, newBytes, 0, readBytes);

            UnityThread.executeInUpdate(() =>
            {
                ClientHandleData.HandleData(newBytes);
            });

            myStream.BeginRead(receiveBuffer, 0, 4096 * 2, ReceiveCallback, null);
        }
        catch (Exception)
        {
            throw;
        }
    }
        private static void OnPlayerDied(PlayerLife sender, EDeathCause cause, ELimb limb, CSteamID instigator)
        {
            var killedSteamPlayer = sender.channel.owner;
            var combat            = CombatManager.CombatTracker.ContainsKey(killedSteamPlayer) ? CombatManager.CombatTracker[killedSteamPlayer] : null;

            if (combat != null && PlayerTool.getSteamPlayer(instigator) == null &&
                DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() -
                combat.LastHit <
                Main.Config.CombatExpiration)
            {
                instigator = combat.Aggressor.playerID.steamID;
            }

            var killInfo = new PlayerDeath(killedSteamPlayer, instigator, cause);

            var killer = PlayerTool.getSteamPlayer(instigator);

            if (killer != null)
            {
                killInfo.KillerShotsHit   = CombatManager.Accuracies.ContainsKey(killer) ? CombatManager.Accuracies[killer].ShotsHit : 0;
                killInfo.KillerShotsFired = CombatManager.Accuracies.ContainsKey(killer) ? CombatManager.Accuracies[killer].ShotsFired : 0;
                UnityThread.executeCoroutine(CaptureScreen(killInfo, killer));
            }
            else
            {
                var socketData = new SocketData("PlayerDeath", JsonConvert.SerializeObject(killInfo));
                SocketManager.Emit(socketData);
            }
        }
Esempio n. 6
0
 // 重置(未使用)
 private void ResetDraw()
 {
     UnityThread.executeInUpdate(() =>
     {
         DestroyAnnotations();
     });
 }
Esempio n. 7
0
        public static void InitDebugMode(string playerUID, int playerCount)
        {
            if (Instance != null)
            {
                return;
            }

            if (playerCount < 1 || playerCount > 8)
            {
                Debug.LogError($"{_debugName}: invalid player count. (Max=8)");
                return;
            }

            _debugMode        = true;
            _debugPlayerCount = playerCount;
            Instance          = new FrameSyncClient(playerUID);
            UnityThread.initUnityThread();
            SWConsole.SetLogger(new UnityLogger());
            SWConsole.level = ConsoleLogLevel.error;

            if (UnityEngine.Application.isPlaying)
            {
                GameObject obj = new GameObject("_SWFrameSyncClientBehaviour");
                //obj.hideFlags = HideFlags.HideAndDontSave;
                SWFrameSyncClientBehaviour cb = obj.AddComponent <SWFrameSyncClientBehaviour>();
                cb.SetClient(Instance);
            }
        }
Esempio n. 8
0
    void DetermineFilterStatusThreaded()
    {
        ImageData temp = Data.act.imageData.Where(tempo => tempo.filename == Path.GetFileName(files[currentIndex])).SingleOrDefault();

        //print("ID: " + temp.id);
        UnityThread.executeInUpdate(() =>
        {
            if (temp != null)
            {
                if (temp.filtered)
                {
                    buttonKeep.interactable   = true;
                    buttonFilter.interactable = false;
                }
                else
                {
                    buttonKeep.interactable   = false;
                    buttonFilter.interactable = true;
                }
                buttonDeleteData.interactable = true;
            }
            else
            {
                buttonKeep.interactable       = true;
                buttonFilter.interactable     = true;
                buttonDeleteData.interactable = false;
            }
        });
    }
        public IEnumerator TestInitialize()
        {
            UnityThread.Initialize();
            var store = new DummyStore();

            yield return(InitStore(store));
        }
Esempio n. 10
0
        public IEnumerator ActionExecuteNextLateUpdate()
        {
            // Wait for a new frame
            yield return(new WaitForEndOfFrame());

            var counter = 0;

            UnityThread.ExecuteInUpdate(() => {
                ++counter;
                Debug.Log("Update loop");
            });
            UnityThread.ExecuteInLateUpdate(() => {
                counter = counter * 2;
                Debug.Log("LateUpdate loop");
            });

            // Runner is spawned
            var runner = GameObject.Find("UnityThreadRunner");

            Assert.NotNull(runner);

            yield return(null);

            LogAssert.Expect(LogType.Log, "Update loop");
            Assert.AreEqual(1, counter);

            yield return(new WaitForEndOfFrame());

            LogAssert.Expect(LogType.Log, "LateUpdate loop");
            Assert.AreEqual(2, counter);
        }
Esempio n. 11
0
        public IEnumerator ActionExecuteNextFixedUpdate()
        {
            // Wait for a new fixed frame
            yield return(new WaitForFixedUpdate());

            Time.fixedDeltaTime = 0.33f;

            var counter = 0;

            UnityThread.ExecuteInFixedUpdate(() => {
                counter += 10;
                Debug.Log("FixedUpdate loop");
            });

            // Runner is spawned
            var runner = GameObject.Find("UnityThreadRunner");

            Assert.NotNull(runner);

            yield return(null);

            Assert.AreEqual(0, counter);

            yield return(new WaitForEndOfFrame());

            Assert.AreEqual(0, counter);

            yield return(new WaitForFixedUpdate());

            LogAssert.Expect(LogType.Log, "FixedUpdate loop");
            Assert.AreEqual(10, counter);
        }
Esempio n. 12
0
        public IEnumerator ActionExecuteNextUpdate()
        {
            var counter = 0;

            UnityThread.ExecuteInUpdate(() => {
                ++counter;
                Debug.Log("Update loop");
            });

            // Runner is spawned
            var runner = GameObject.Find("UnityThreadRunner");

            Assert.NotNull(runner);

            // Counter not yet modified
            Assert.AreEqual(0, counter);

            yield return(null);

            // Logged
            LogAssert.Expect(LogType.Log, "Update loop");

            // Counter increased
            Assert.AreEqual(1, counter);

            yield return(null);

            // Counter not increased any further
            Assert.AreEqual(1, counter);
        }
Esempio n. 13
0
        bool LoadNext(Action <Homework.Period> onComplete = null)
        {
            if (!periodsMethod.MoveNext())
            {
                return(false);
            }
            UnityThread.executeCoroutine(enumerator());
            return(true);

            IEnumerator enumerator()
            {
                var value = periodsMethod.Current;

                while (value == null)
                {
                    yield return(new WaitForEndOfFrame());

                    if (!periodsMethod.MoveNext())
                    {
                        break;
                    }
                    value = periodsMethod.Current;
                }
                periods.Add(value);
                onComplete?.Invoke(value);
            }
        }
Esempio n. 14
0
            public override void execute(CSteamID executor, string[] args)
            {
                SteamPlayer player = PlayerTool.getSteamPlayer(executor);

                if (Main.Config.allowToggle || player.isAdmin)
                {
                    if (enabledNameplatesList.Contains(player.playerID.steamID))
                    {
                        enabledNameplatesList.Remove(player.playerID.steamID);
                        disabledNameplatesList.Add(player.playerID.steamID);
                        UnityThread.executeInUpdate(() =>
                        {
                            ChatManager.say(player.playerID.steamID, $"Nameplate disabled", Color.cyan);
                        });
                    }
                    else
                    {
                        disabledNameplatesList.Remove(player.playerID.steamID);
                        enabledNameplatesList.Add(player.playerID.steamID);
                        UnityThread.executeInUpdate(() =>
                        {
                            ChatManager.say(player.playerID.steamID, $"Nameplate enabled", Color.cyan);
                        });
                    }
                }
            }
Esempio n. 15
0
 public void turnIndicatorOff()
 {
     UnityThread.executeInUpdate(() =>
     {
         indicatorRenderer.material = offMaterial;
     });
 }
        public IEnumerator TestImport()
        {
            UnityThread.Initialize();
            var store = new DummyStore();

            yield return(InitStore(store));

            var listeners = new List <TaskListener <DummyIndex> >()
            {
                new TaskListener <DummyIndex>(),
                new TaskListener <DummyIndex>(),
                new TaskListener <DummyIndex>()
            };

            for (int i = 0; i < listeners.Count; i++)
            {
                yield return(WaitImport(store, i, listeners[i]));

                var value = listeners[i].Value;
                Assert.IsNotNull(value);
                Assert.AreEqual($"00000000-0000-0000-0000-00000000000{i}", value.Id.ToString());
                Assert.AreEqual($"Name{i}", value.Name);
                Assert.AreEqual(i, value.Age);
                Assert.AreEqual(i % 2 == 1, value.IsVerified);
            }
            Assert.AreEqual(3, store.Count);
        }
Esempio n. 17
0
        public void RemoveById(string id, bool multiple)
        {
            if (string.IsNullOrEmpty(id))
            {
                return;
            }

            UnityThread.DispatchUnattended(() =>
            {
                for (int i = notifications.Count - 1; i >= 0; i--)
                {
                    var notif = notifications[i];
                    if (notif.Id == id)
                    {
                        notifications.RemoveAt(i);
                        OnRemoveNotification?.Invoke(notif);
                        if (!multiple)
                        {
                            return(null);
                        }
                    }
                }
                return(null);
            });
        }
Esempio n. 18
0
        public IEnumerator CoroutineExecutedNextUpdate()
        {
            UnityThread.ExecuteCoroutine(ACoroutine());

            // Runner is spawned
            var runner = GameObject.Find("UnityThreadRunner");

            Assert.NotNull(runner);

            // Counter not yet modified
            Assert.AreEqual(0, counter);

            yield return(null);

            // 0.3 sec has not passed, counter should not been increased
            Assert.AreEqual(0, counter);

            yield return(new WaitForSeconds(0.3f));

            Assert.AreEqual(1, counter);
            yield return(new WaitForSeconds(0.4f));

            Assert.AreEqual(2, counter);
            yield return(new WaitForSeconds(0.6f));

            Assert.AreEqual(4, counter);
            yield return(new WaitForSeconds(1f));

            Assert.AreEqual(5, counter);
        }
Esempio n. 19
0
    void SetSpeed(object o, System.EventArgs e)
    {
        timer.Stop();

        UnityThread.executeInUpdate(() =>
        {
            rnd = UnityEngine.Random.Range(0, 4);
        });

        switch (rnd)
        {
        case 0:
            speed = Speed.SLOW;
            break;

        case 1:
            speed = Speed.MEDIUM;
            break;

        case 2:
            speed = Speed.FAST;
            break;

        case 3:
            speed = Speed.STOP;
            break;

        default:
            break;
        }

        timer.Start();
    }
Esempio n. 20
0
 private void RewardUser(NimbusAdUnit ad, bool skipped)
 {
     if (_ad?.InstanceID != ad.InstanceID)
     {
         return;
     }
     if (!skipped)
     {
         Debug.unityLogger.Log(
             $"NimbusEventListenerExample Ad was rendered for ad instance {ad.InstanceID}, " +
             $"bid value: {ad.ResponseMetaData.BidRaw}, " +
             $"bid value in cents: {ad.ResponseMetaData.BidInCents}, " +
             $"network: {ad.ResponseMetaData.Network}, " +
             $"placement_id: {ad.ResponseMetaData.PlacementID}, " +
             $"auction_id: {ad.ResponseMetaData.AuctionID}");
         // ensures that this coroutine starts on the Unity Main thread since this is called within an event callback
         UnityThread.ExecuteInUpdate(() => StartCoroutine(MakeItRain()));
         return;
     }
     Debug.unityLogger.Log(
         $"NimbusEventListenerExample Ad was rendered for ad instance, however the user skipped the ad {ad.InstanceID}, " +
         $"bid value: {ad.ResponseMetaData.BidRaw}, " +
         $"bid value in cents: {ad.ResponseMetaData.BidInCents}, " +
         $"network: {ad.ResponseMetaData.Network}, " +
         $"placement_id: {ad.ResponseMetaData.PlacementID}, " +
         $"auction_id: {ad.ResponseMetaData.AuctionID}");
 }
Esempio n. 21
0
    //RECEIVE DATA CALLBACK
    private static void OnReceiveData(IAsyncResult result)
    {
        try
        {
            int length = stream.EndRead(result);
            if (length <= 0)
            {
                return;
            }

            byte[] newBytes = new byte[length];
            Array.Copy(receiveBuffer, newBytes, length);
            UnityThread.executeInFixedUpdate(() =>
            {
                DataReceiver.HandleData(newBytes);
            });

            stream.BeginRead(receiveBuffer, 0, 4096 * 2, OnReceiveData, null);
            DataReceiver.playerBuffer.Clear();
        }
        catch (Exception)
        {
            return;
        }
    }
Esempio n. 22
0
        //If the Welcome Message arrives
        //it begins to endless loop all other Messages in different Unity Thread
        private static void ReceiveCallback(IAsyncResult result)
        {
            try
            {
                int length = myStream.EndRead(result);
                if (length <= 0)
                {
                    return;
                }


                byte[] newBytes = new byte[length];
                Array.Copy(recBuffer, newBytes, length);
                UnityThread.executeInFixedUpdate(() =>
                {
                    ClientHandleData.HandleData(newBytes);
                });
                //Infinte Loop
                myStream.BeginRead(recBuffer, 0, 4096 * 2, ReceiveCallback, null);
            }

            catch (Exception)
            {
                //NetworkManager.instance.DestroyLocalPlayer();
                return;
            }
        }
 void Start()
 {
     DontDestroyOnLoad(this);
     UnityThread.initUnityThread();
     ClientHandleData.InitializePackets();
     ClientTCP.InitializingNetworking();
 }
Esempio n. 24
0
    void SetDirection(object o, System.EventArgs e)
    {
        timer.Stop();

        UnityThread.executeInUpdate(() =>
        {
            rnd = UnityEngine.Random.Range(0, 2);
        });

        switch (rnd)
        {
        case 0:
            direction = Direction.LEFT;
            break;

        case 1:
            direction = Direction.RIGHT;
            break;

        default:
            break;
        }

        timer.Start();
    }
 public void OnSendMessage(int tabId, string text)
 {
     if (this.m_Chat != null)
     {
         UnityThread.executeInUpdate(() => this.m_Chat.ReceiveChatMessage(tabId, "<color=#" + CommonColorBuffer.ColorToString(this.m_PlayerColor) + "><b>" + this.m_PlayerName + "</b></color> <color=#59524bff>said:</color> " + text));
     }
 }
Esempio n. 26
0
        private void OnReceiveData(IAsyncResult result)
        {
            try
            {
                int packetLength = myStream.EndRead(result);
                receivedBytes = new byte[packetLength];
                Buffer.BlockCopy(asyncBuffer, 0, receivedBytes, 0, packetLength);

                if (packetLength == 0)
                {
                    Debug.LogWarning("서버와의 접속이 끊겼습니다.");
                    UnityThread.ExecuteInUpdate(() =>
                    {
                        Application.Quit();
                    });
                    return;
                }
                UnityThread.ExecuteInUpdate(() =>
                {
                    NetworkHandleData.HandleData(receivedBytes);
                });
                myStream.BeginRead(asyncBuffer, 0, NetworkSettings.CLIENT_BUFFERSIZE * 2, OnReceiveData, null);
            }
            catch (Exception)
            {
                Debug.LogWarning("서버와의 접속이 끊겼습니다.");
                UnityThread.ExecuteInUpdate(() =>
                {
                    Application.Quit();
                });
                return;
            }
        }
 // receive thread
 private void ReceiveData()
 {
     try {
         Byte[] bytes = new Byte[1024];
         while (true)
         {
             // Get a stream object for reading
             using (NetworkStream stream = client.GetStream()) {
                 int length;
                 // Read incomming stream into byte arrary.
                 while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                 {
                     var data = new byte[length];
                     Array.Copy(bytes, 0, data, 0, length);
                     // Convert byte array to string message.
                     string serverMessage = Encoding.ASCII.GetString(data);
                     Debug.Log("server message received as: " + serverMessage);
                     UnityThread.executeInUpdate(() =>
                     {
                         if (data[0] == 255 && data[1] == 216 && data[2] == 255 && data[3] == 224 && data[4] == 0 && data[5] == 16 && data[6] == 74 && data[7] == 70 && data[8] == 73 && data[9] == 70)
                         {
                             //UnityEngine.Debug.Log("* texture *");
                             tex.LoadImage(data);
                             rawImage.material.mainTexture = tex;
                         }
                     });
                 }
             }
         }
     }
     catch (SocketException socketException) {
         Debug.Log("Socket exception: " + socketException);
         Debug.Log("Error trying to read...");
     }
 }
Esempio n. 28
0
        protected override void ParseResponseData(JToken responseData)
        {
            Task.Run(() =>
            {
                try
                {
                    var data = responseData.ToObject <JObject>();
                    Mapsets  = data["mapsets"].ToObject <OnlineMapset[]>();
                    if (data.ContainsKey("cursor"))
                    {
                        Cursor = data["cursor"].ToString();
                    }
                    if (data.ContainsKey("total"))
                    {
                        Total = data["total"].Value <int>();
                    }

                    UnityThread.DispatchUnattended(() =>
                    {
                        EvaluateSuccess();
                        return(null);
                    });
                }
                catch (Exception e)
                {
                    UnityThread.DispatchUnattended(() =>
                    {
                        EvaluateFail(e.Message);
                        return(null);
                    });
                }
            });
        }
Esempio n. 29
0
        /// <summary>
        /// Бесконечно дописывает логи в файл.
        /// </summary>
        /// <param name="state"></param>
        private async void ThreadWork(object state)
        {
            try
            {
                while (true)
                {
                    await Task.Delay(maxPrintingPeriodMs);

                    string[] logsCopy = new string[logs.Count];
                    lock (LockObj)
                    {
                        if (logs.Count > 0)
                        {
                            logs.CopyTo(logsCopy);
                            logs.Clear();
                        }
                    }
                    Print(logsCopy);
                }
            }
            catch (Exception e)
            {
                UnityThread.Execute(() =>
                {
                    Debug.LogError("Было брошено исключение в логгере " + e.Message);
                });
            }

            // ReSharper disable once FunctionNeverReturns
        }
Esempio n. 30
0
        public static bool Initialise(DateTime start, Action <TimeRange, List <ScheduledEvent> > action)
        {
            if (Screen.width <= Screen.height)
            {
                periodStart = start.Date;
            }
            int delta = DayOfWeek.Monday - start.DayOfWeek;

            start = start.AddDays(delta > 0 ? delta - 7 : delta);
            if (Screen.width > Screen.height)
            {
                periodStart = start.Date;
            }
            var period = new TimeRange(start, start + new TimeSpan(6, 0, 0, 0));

            if (!Manager.provider.TryGetModule(out Integrations.Schedule module))
            {
                Manager.instance.transform.Find("Schedule").gameObject.SetActive(false); return(false);
            }
            var dayList   = period.DayList();
            var _schedule = Manager.Data.ActiveChild.Schedule?.Where(h => dayList.Contains(h.start.Date)).ToList();

            if (_schedule?.Count > 0)
            {
                action(period, _schedule);
            }
            else
            {
                UnityThread.executeCoroutine(module.GetSchedule(period, (schedule) => action(period, schedule.ToList())));
            }
            return(true);
        }