Example #1
0
	//-------------------------------------------------------------------------------------------------------------------------
	void Awake()
	{

		if (Singleton != null)
		{
			UnityEngine.Debug.LogError("Multiple Dbg Singletons exist!");
			return;
		}

		Singleton = this;

#if !FINAL
		// Open the log file to append the new log to it.
		OutputStream = new StreamWriter( LogFile, true );
#endif
	}
Example #2
0
        public static void GetAvrStyles
            (long layoutId, out string gradLayerName, out ITheme gradLayerTheme, out string chartLayerName,
            out ITheme chartLayerTheme)
        {
            gradLayerTheme  = null;
            chartLayerTheme = null;
            gradLayerName   = chartLayerName = string.Empty;


            #region Get layer settings

            const string TasLayout = "tasLayout";
            byte[]       GisLayerLocalSettingsZip;
            string       GisLayerLocalSettingsXml;
            XmlDocument  xmlSetting = null;

            try
            {
                var ds = new DataSet();
                //IDbCommand cmd = CreateSPCommand("spAsMapSettingsSelectDetail");

                var cmd = new SqlCommand("spAsMapSettingsSelectDetail",
                                         (SqlConnection)ConnectionManager.DefaultInstance.Connection)
                {
                    CommandTimeout = 300,
                    CommandType    = CommandType.StoredProcedure
                };

                cmd.Parameters.Add(new SqlParameter("@LangID", ModelUserContext.CurrentLanguage));
                cmd.Parameters.Add(new SqlParameter("@LayoutID", layoutId));

                DbDataAdapter adapter = new SqlDataAdapter(cmd);

                adapter.Fill(ds, TasLayout);
                ds.EnforceConstraints = false;
                if (ds.Tables[TasLayout].Rows.Count > 0)
                {
                    DataRow row = ds.Tables[TasLayout].Rows[0];
                    if (bv.common.Core.Utils.IsEmpty(row["blbGisLayerGeneralSettings"]))
                    {
                        return;
                    }
                    GisLayerLocalSettingsZip = (byte[])row["blbGisLayerGeneralSettings"];
                    GisLayerLocalSettingsXml = BinaryCompressor.UnzipString(GisLayerLocalSettingsZip);
                    xmlSetting = new XmlDocument();
                    xmlSetting.LoadXml(GisLayerLocalSettingsXml);
                    ds.EnforceConstraints = true;
                }
            }
            catch (Exception ex)
            {
                Dbg.Debug(ex.ToString());
                return;
            }

            #endregion

            if (xmlSetting == null)
            {
                return;
            }

            var tmpGroup =
                GIS_V4.Serializers.LayerSerializers.LayerGroupSerializer.Instance.Deserialize(
                    (XmlElement)xmlSetting.ChildNodes[0]);

            foreach (var layer in tmpGroup.Layers)
            {
                if (layer is LabelLayer)
                {
                    continue;
                }
                ((EventLayer)layer).Theme = ReplaceColumnName((EventLayer)layer);

                if ((string)layer.Tag == "event_gradient")
                {
                    gradLayerName  = layer.LayerName;
                    gradLayerTheme = ((VectorLayer)layer).Theme;
                }
                if ((string)layer.Tag == "event_chart")
                {
                    chartLayerName  = layer.LayerName;
                    chartLayerTheme = ((VectorLayer)layer).Theme;
                }
            }
        }
Example #3
0
    GameObject InstantiateSelf(List <GameObject> previouslyInstantiated)
    {
        if (instantiated != null)
        {
            return(instantiated);
        }

        if (prefab == null)
        {
            return(null);
        }

        if (previouslyInstantiated.Contains(prefab))
        {
            Dbg.LogError(
                this,
                "{0} was already instantiated in this hierarchy. It will not be instantiated to avoid recursion.",
                this
                );
            return(null);
        }

        if (prefab == gameObject)
        {
            Dbg.LogError(
                this,
                "{0} had itself as prefab. It will not be instantiated to avoid recursion.",
                this
                );
            return(null);
        }

        previouslyInstantiated.Add(prefab);

#if UNITY_EDITOR
        if (EditorApplication.isPlayingOrWillChangePlaymode)
        {
            instantiated = GameObject.Instantiate(prefab);
        }
        else
        {
            instantiated = PrefabUtility.InstantiatePrefab(
                prefab,
                destinationScene: gameObject.scene
                ) as GameObject;
        }
#else
        instantiated = GameObject.Instantiate(prefab);
#endif // UNITY_EDITOR

        if (instantiated != null)
        {
            instantiated.transform.parent        = transform;
            instantiated.transform.localPosition = Vector3.zero;
            instantiated.transform.localRotation = Quaternion.identity;
            instantiated.transform.localScale    = Vector3.one;
        }

        instantiated.name = prefab.name;

        return(instantiated);
    }
Example #4
0
 void Start()
 {
     Dbg.LogCheckAssigned(BossCache, this);
 }
Example #5
0
        internal override ICacheClient TryExecute(ICacheClient client)
        {
            if (!CanExecute)
            {
                return(null);
            }


            Dbg.CheckThat(Params.Count <= 1);


            try
            {
                Profiler.IsActive = true;
                Profiler.Start("DESC");

                var serverInfo = client.GetClusterInformation();


                ProfilingData profilerResult = Profiler.End();


                if (Params.Count == 1)
                {
                    string tableName = Params[0];
                    foreach (var typeDescription in serverInfo.Schema)
                    {
                        if (tableName.ToUpper() == typeDescription.TypeName.ToUpper())
                        {
                            LogTypeInfo(typeDescription);
                            break;
                        }
                    }
                }
                else
                {
                    foreach (var info in serverInfo.ServersStatus)
                    {
                        Logger.Write("");
                        Logger.Write("Server process");
                        Logger.Write("----------------------------------------------------------------------------");

                        //Logger.Write("    server name  = {0}", serverInfo.ServerProcessInfo.Host);
                        Logger.Write("      image type = {0} bits", info.Bits);
                        Logger.Write("      started at = {0}", info.StartTime);
                        Logger.Write("  active clients = {0}", info.ConnectedClients);
                        Logger.Write("         threads = {0}", info.Threads);
                        Logger.Write(" physical memory = {0} MB", info.WorkingSet / 1000000);
                        Logger.Write("  virtual memory = {0} MB", info.VirtualMemory / 1000000);
                        Logger.Write("software version = {0} ", info.SoftwareVersion);
                        Logger.Write("");
                    }

                    Logger.Write("Tables");
                    Logger.Write("-----------------------------------------------------------------------------");

                    string header =
                        $"| {"Name",15} | {"Zip",5} |";

                    Logger.Write(header);
                    Logger.Write("-----------------------------------------------------------------------------");

                    foreach (var typeDescription in serverInfo.Schema)
                    {
                        string compression = typeDescription.UseCompression.ToString();



                        Logger.Write("| {0,15} | {1,5} |",
                                     typeDescription.TypeName,
                                     compression
                                     );
                    }

                    Logger.Write("-----------------------------------------------------------------------------");
                }


                Logger.Write("The call took {0} milliseconds", profilerResult.TotalTimeMiliseconds);
            }
            catch (Exception ex)
            {
                Profiler.End();
                Logger.WriteEror("Can not execute DESC : {0}", ex.Message);

                return(null);
            }


            return(client);
        }
Example #6
0
        public void Execute()
        {
            //Debug.Log($"InputController.Execute - IsActive: {IsActive}, Input.GetKeyDown({Input.GetKeyDown(_activeFlashLight)})");
            if (!IsActive)
            {
                return;
            }
            if (Input.GetKeyDown(_activeFlashLight))
            {
                ServiceLocator.Resolve <FlashLightController>().Switch(); //todo сделать вариант смены фонарика
                //Switch(ServiceLocator.Resolve<Inventory>().FlashLight);
            }

            if (Input.GetKeyDown(_selectWeapon1))
            {
                SelectWeapon(0);
            }

            if (Input.GetKeyDown(_selectWeapon2))
            {
                SelectWeapon(1);
            }

            if (Input.GetKeyDown(_selectWeapon3))
            {
                SelectWeapon(2);
            }

            if (Input.GetKeyDown(_selectWeapon4))
            {
                SelectWeapon(3);
            }
            if (Input.GetKeyDown(_selectWeapon5))
            {
                SelectWeapon(4);
            }
            if (Input.GetKeyDown(_selectWeapon6))
            {
                SelectWeapon(5);
            }


            //if (Math.Abs(Input.GetAxis("Mouse ScrollWheel") - _cashMouseScrollWheel) > 0.1f)
            Dbg.Log($"Vector2 scroll = Input.mouseScrollDelta; {Input.mouseScrollDelta.y}");
            //todo работает очень криво
            if (Input.mouseScrollDelta.y > _cashMouseScrollWheel)
            {
                _cashMouseScrollWheel = Input.mouseScrollDelta.y;
                SelectWeapon(ServiceLocator.Resolve <Inventory>().GetLastIndexWeapon() + 1);
            }
            if (Input.mouseScrollDelta.y < _cashMouseScrollWheel)
            {
                _cashMouseScrollWheel = Input.mouseScrollDelta.y;
                SelectWeapon(ServiceLocator.Resolve <Inventory>().GetLastIndexWeapon() - 1);
            }


            if (Input.GetMouseButton(_mouseButton))
            {
                if (ServiceLocator.Resolve <WeaponController>().IsActive)
                {
                    ServiceLocator.Resolve <WeaponController>().Fire();
                }
            }

            if (Input.GetKeyDown(_cansel))
            {
                ServiceLocator.Resolve <WeaponController>().Off();
                ServiceLocator.Resolve <FlashLightController>().Off();
            }

            if (Input.GetKeyDown(_reloadClip))
            {
                if (ServiceLocator.Resolve <WeaponController>().IsActive)
                {
                    ServiceLocator.Resolve <WeaponController>().ReloadClip();
                }
            }
        }
Example #7
0
 void BeginShutdownScope(string name)
 {
     Dbg.LogRelease(this, "APP: Shutting down {0}...", name);
     scopeStopwatch = Stopwatch.StartNew();
 }
Example #8
0
 void BeginSetupScope(string name)
 {
     Dbg.LogRelease(this, "APP: Setting up {0}...", name);
     scopeStopwatch = Stopwatch.StartNew();
 }
Example #9
0
 public void EnterGame()
 {
     Dbg.DEBUG_MSG("Account::enterGame");
     this.baseEntityCall.enterGame();
 }
Example #10
0
 public override void onFirstEntityHello(string content)
 {
     Dbg.DEBUG_MSG("Account::onFirstEntityHello:content=\r\n" + content);
     KBEngine.Event.fireOut("Event_OnFirstEntityHello", content);
 }
Example #11
0
 public override void onEnterGameSuccess()
 {
     Dbg.DEBUG_MSG("Account::onEnterGameSuccess!");
     KBEngine.Event.fireOut("Event_OnEnterGameSuccess");
 }
Example #12
0
 public override void onEnterGameFailed(sbyte errorCode)
 {
     Dbg.ERROR_MSG("Account::onEnterGameFailed: errorCode=" + errorCode);
     KBEngine.Event.fireOut("Event_OnEnterGameFailed", errorCode);
 }
Example #13
0
 public VELst GetActiveVEdges()
 {
     Dbg.Assert(m_activeVELst != null, "VVert.GetActiveVEdges: the activeVELst is null");
     return(m_activeVELst);
 }
Example #14
0
            // "edge"

            public void AddVEdge(VEdge e)
            {
                Dbg.Assert(!m_veLst.Contains(e), "VVert.AddVEdge: the edge already in vvert: {0}", this.RepVert);
                m_veLst.Add(e);
            }
Example #15
0
        /// <summary>
        /// 1. rotate bone back from current rotation to refAxis; angle is "X"
        /// 2. clamp X;
        /// 3. rotate back with clamped X;
        /// 4. calculate and clamp twist;
        /// </summary>
        public override void Apply(ISolver solver, int jointIdx)
        {
            if (m_nextJoint == null)
            {
                Dbg.CLogWarn(this, "ConeConstraintMB.Apply: nextJoint not set: {0}", name);
                return;
            }
            Dbg.CAssert(this, m_angleLimit >= 0, "ConeConstraintMB.Apply: m_angleLimit should >= 0, but: {0}", m_angleLimit);
            Dbg.CAssert(this, -180f <= m_minTwistLimit && m_minTwistLimit <= 180f, "ConeConstraintMB.Apply: minTwistLimit: {0}", m_minTwistLimit);
            Dbg.CAssert(this, -180f <= m_maxTwistLimit && m_maxTwistLimit <= 180f, "ConeConstraintMB.Apply: maxTwistLimit: {0}", m_maxTwistLimit);
            Dbg.CAssert(this, 0 <= m_angleLimit && m_angleLimit <= 180f, "ConeConstraintMB.Apply: angleLimit: {0}", m_angleLimit);

            var       joints = solver.GetJoints();
            Transform j      = joints[jointIdx];
            Transform cj     = m_nextJoint;
            Transform pj     = j.parent;

            //1
            Vector3    boneDirWorld = cj.position - j.position;
            Vector3    refDirWorld = Misc.TransformDirection(pj, m_refAxis);
            Quaternion q = Quaternion.FromToRotation(boneDirWorld, refDirWorld);
            float      angle; Vector3 rotAxis;

            q.ToAngleAxis(out angle, out rotAxis);
            angle = Misc.NormalizeAnglePI(angle);

            j.rotation = q * j.rotation;
            //Dbg.Log("coneconstraint: angle: {0}, rotAxis: {1}", angle, rotAxis);

            //2
            angle = Mathf.Clamp(angle, -m_angleLimit, m_angleLimit);

            //3
            j.Rotate(rotAxis, -angle, Space.World);

            //4
            if (m_limitTwist)
            { //use swing-twist decomposition of quaternion to limit twist
                Quaternion deltaRot = j.localRotation * Quaternion.Inverse(m_initRot);

                Vector3    curTwistAxisDirWorld  = (m_nextJoint.position - tr.position).normalized;
                Vector3    curTwistAxisDirParent = Misc.InverseTransformDirection(pj, curTwistAxisDirWorld);
                Quaternion swingRot = Quaternion.FromToRotation(m_twistAxis, curTwistAxisDirParent);
                Quaternion twistRot = Quaternion.Inverse(swingRot) * deltaRot;

                Vector3 tmpAxis; float twist;
                twistRot.ToAngleAxis(out twist, out tmpAxis);
                twist = Misc.NormalizeAnglePI(twist);
                if (float.IsInfinity(tmpAxis.x)) //SPECIAL case, some extreme data will make tmpAxis to be <inf,inf,inf>
                {
                    tmpAxis = Vector3.right;
                    twist   = 0;
                }
                if (Misc.IsObtuseAngle(tmpAxis, m_twistAxis))
                {
                    twist   = -twist;
                    tmpAxis = -tmpAxis;
                }

                twist    = Mathf.Clamp(twist, m_minTwistLimit, m_maxTwistLimit);
                twistRot = Quaternion.AngleAxis(twist, tmpAxis);
                deltaRot = swingRot * twistRot;

                var applied = deltaRot * m_initRot;
                j.localRotation = applied;
            }
        }
Example #16
0
    void OnSceneWillUnload()
    {
        Dbg.LogRelease(this, "APP: Scene will unload");

        ShutdownState();
    }
 void Start()
 {
     AmmoCountText = GetComponent <Text>();
     Dbg.LogCheckAssigned(AmmoCountText);
 }
Example #18
0
 void BeginLoadingScope(string msg)
 {
     Dbg.LogRelease(this, "APP: Loading - {0}...", msg);
     scopeStopwatch = Stopwatch.StartNew();
 }
Example #19
0
 public override void onEnter()
 {
     Dbg.INFO_MSG("PlayerAvatar::onEnter");
     this.baseEntityCall.reqMatch();
 }
Example #20
0
 void EndShutdownScope()
 {
     scopeStopwatch.Stop();
     Dbg.LogRelease(this, "APP: Took {0:00}.{1:000}s", scopeStopwatch.Elapsed.Seconds, scopeStopwatch.Elapsed.Milliseconds);
 }
Example #21
0
 public override void onEnterSpace()
 {
     Dbg.INFO_MSG("onEnterSpace, " + KBEngineApp.app.spaceID);
 }
Example #22
0
    // Update is called once per frame
    void FixedUpdate()
    {
        if (Game.isOver)
        {
            return;
        }

        if (attractedComponent.AttractorList.Count == 0)
        {
            return;
        }

        if (attractedComponent.lastLand == null)
        {
            return;
        }

//		if (Time.time > nextBoostTime && remainingBoost < maxBoost) {
//			//			canBoost = true;
//			remainingBoost++;
//			nextBoostTime = Time.time + boostIncreaseDelay;
//		}

        int h = (int)Input.GetAxisRaw("Horizontal");
        int v = (int)Input.GetAxisRaw("Vertical");

        Rigidbody2D body = GetComponent <Rigidbody2D> ();

        bool hasMoved = false;

        if (h != 0)
        {
            hasMoved = true;

            Dbg.Log(this, "attractors", attractedComponent.AttractorList.Count);

            transform.localScale = new Vector3(-Mathf.Abs(transform.localScale.x) * h, transform.localScale.y, transform.localScale.z);

            animator.SetTrigger("startWalking");

            Dbg.Log(this, "animator", animator);


            if (attractedComponent.AttractorList.Count > 0)
            {
                Vector2 walkForce = new Vector2(h, 0);

                walkForce = walkForce.Rotate(body.transform.rotation.eulerAngles.z);
                body.AddForce(walkForce * acceleration);
            }
            else
            {
                body.AddTorque(-(float)h);
            }
        }
        else
        {
            animator.SetTrigger("stopWalking");
        }

        if (body.velocity.magnitude > 0)
        {
            if (body.velocity.magnitude > maxSpeed)
            {
                body.velocity = body.velocity.normalized * maxSpeed;
            }

            float   vComponent  = 1 - body.drag;
            Vector2 decelerated = body.velocity.Clone();
            decelerated.x *= vComponent;
            decelerated.y *= vComponent;
            body.velocity  = decelerated;
        }

//		if (v > 0 && (GetComponent<GravityAttracted>().land || currentJumpLevel < nbJumpLevels)) {
//			currentJumpLevel++;
//			Vector2 jumpForce = new Vector2 (0, jumpFactor);
//			Dbg.Log (this, "jumpForce", jumpForce.magnitude);
//			jumpForce = jumpForce.Rotate (body.transform.rotation.eulerAngles.z);
//			Dbg.Log (this, "jumpForce", jumpForce.magnitude);
//			body.AddForce (jumpForce);
//		}

        if (v > 0)
        {
            hasMoved  = true;
            hasJumped = true;

            if (attractedComponent.AttractorList.Count > 1)
            {
                attractedComponent.ignoreOrientation = true;
            }

//			if (attractedComponent.land != null) {
//				AudioSource source = GetComponent<AudioSource> ();
//				source.clip = jumpSounds [Rnd.Int (0, jumpSounds.Length)];
//				source.pitch = Rnd.Float (0.95f, 1.05f);
//				source.Play ();
//			}
//				SoundManager.instance.RandomizeSfx (jumpSounds);

//			if(remainingBoost > 0) {
//				remainingBoost--;
//				Vector2 boostForce = new Vector2 (0, jumpFactor);
//				boostForce = boostForce.Rotate (body.transform.rotation.eulerAngles.z);
//				body.AddForce (boostForce);
//			}
            Dbg.Log(this, "jump", jumpLevel, maxJumpLevel);
            if (jumpLevel < maxJumpLevel)
            {
                jumpLevel++;
            }
        }
        else
        {
            if (jumpLevel > 0)
            {
                attractedComponent.ignoreOrientation = false;
                Vector2 boostForce = new Vector2(0, jumpFactor);
                boostForce = boostForce.Rotate(body.transform.rotation.eulerAngles.z);
                body.AddForce(boostForce);
                jumpLevel--;

                if (attractedComponent.land != null)
                {
                    AudioSource source = GetComponent <AudioSource> ();
                    source.clip  = jumpSounds [Rnd.Int(0, jumpSounds.Length)];
                    source.pitch = Rnd.Float(0.95f, 1.05f);
                    source.Play();
                }
            }
        }

        if (hasMoved)
        {
            moved.Invoke();
        }
    }
Example #23
0
 public override void enterBattleSpace()
 {
     Dbg.INFO_MSG("PlayerAvatar::enterBattleSpace");
     SceneManager.LoadScene("MainGame");
 }
Example #24
0
        void ProcessResp()
        {
            m_timer.Stop();
            Dbg.Log("Processing start notification resp...");

            string tmpFile  = Path.GetTempFileName();
            var    netEngin = new NetEngin(Program.NetworkSettings);

            try
            {
                netEngin.Download(tmpFile, Urls.ConnectionRespURL, true);

                IEnumerable <Message> resps = from msg in DialogEngin.ReadConnectionsResp(tmpFile)
                                              where msg.ReqID >= m_reqID
                                              select msg;

                if (resps.Any())
                {
                    Message resp = resps.SingleOrDefault(m => m.ReqID == m_reqID);

                    if (resp != null)
                    {
                        var  ms     = new MemoryStream(resp.Data);
                        var  reader = new RawDataReader(ms, Encoding.UTF8);
                        uint clID   = reader.ReadUInt();

                        if (clID == m_clID)
                        {
                            switch (resp.MessageCode)
                            {
                            case Message_t.Ok:
                                m_callBack.Invoke(true);
                                Dbg.Log("Starting notification done. :-)");
                                return;

                            case Message_t.Rejected:
                                m_callBack.Invoke(false);
                                Dbg.Log("Starting rejected. :-(");
                                return;
                            }
                        }
                    }

                    Dbg.Log("Starting msg lost. Reposting...");
                    PostReq();
                }
                else if (++m_cnxAttempts >= MAX_ATTEMPTS)
                {
                    Dbg.Log("Starting msg lost. Reposting...");
                    PostReq();
                }
                else
                {
                    m_timer.Start();
                }
            }
            catch (Exception ex)
            {
                Dbg.Log(ex.Message);
                m_timer.Start();
            }
            finally
            {
                File.Delete(tmpFile);
            }
        }
Example #25
0
        internal override IDataClient TryExecute(IDataClient client)
        {
            if (!CanExecute)
            {
                return(client);
            }

            Dbg.CheckThat(Params.Count == 2);

            IList <JObject> listResult = null;

            try
            {
                Dbg.CheckThat(Query != null);

                Profiler.IsActive = true;
                Profiler.Start("SEARCH");

                listResult = client.GetMany(Query).Select(r => r.Item).Cast <JObject>().ToList();



                Logger.Write("[");
                for (var i = 0; i < listResult.Count; i++)
                {
                    Logger.Write(listResult[i].ToString());
                    if (i < listResult.Count - 1)
                    {
                        Logger.Write(",");
                    }
                }

                Logger.Write("]");

                Logger.DumpFile("ftresult.json");

                Logger.Write("[");
                for (var i = 0; i < listResult.Count; i++)
                {
                    Logger.Write(listResult[i].ToString());
                    if (i < listResult.Count - 1)
                    {
                        Logger.Write(",");
                    }
                }

                Logger.Write("]");
                Logger.EndDump();

                return(client);
            }
            catch (CacheException ex)
            {
                Logger.WriteEror("Can not execute SEARCH : {0} {1}", ex.Message, ex.ServerMessage);
                return(client);
            }
            catch (Exception ex)
            {
                Logger.WriteEror("Can not execute SEARCH : {0}", ex.Message);
                return(client);
            }
            finally
            {
                Profiler.End();

                var count = 0;
                if (listResult != null)
                {
                    count = listResult.Count;
                }

                Logger.Write("Found {0} items. The call took {1} milliseconds", count,
                             Profiler.TotalTimeMilliseconds);
            }
        }
Example #26
0
        public IPersistentTransaction StartProcessing()
        {
            _queueNotEmpty.WaitOne();


            if (_disposed)
            {
                return(null);           // to avoid a race condition between the disposal of consumer and the log
            }
            Dbg.Trace("start processing transaction from transaction log");

            // the event was set during dispose to unlock the consumer
            if (_transactionQueue.Count == 0)
            {
                return(null);
            }


            TransactionData data;

            lock (_syncRoot)
            {
                if (_transactionQueue.Count == 0)
                {
                    return(null);
                }
                data = _transactionQueue.Peek();
            }

            // if it is a delayed transaction wait until it is valid
            if (data.DelayInMilliseconds != 0)
            {
                Dbg.Trace("processing delayed transaction");

                var millisecondsToWait =
                    data.DelayInMilliseconds - (int)(DateTime.Now - data.TimeStamp).TotalMilliseconds;
                if (millisecondsToWait > 0 && data.TransactionStatus != TransactionStatus.Canceled)
                {
                    Dbg.Trace($"waiting {millisecondsToWait} ms for delayed transaction to become active");
                    SmartSleep(millisecondsToWait);
                }
            }

            // if canceled do not process
            if (data.TransactionStatus == TransactionStatus.Canceled)
            {
                Dbg.Trace("delayed transaction was canceled");
                return(null);
            }

            if (data.TransactionStatus != TransactionStatus.ToProcess)
            {
                Dbg.Trace("Incomplete transaction found. Reprocessing");
            }

            lock (_syncRoot)
            {
                data.TransactionStatus = TransactionStatus.Processing;
                UpdateTransactionStatus(data);
            }

            Dbg.Trace("processing delayed transaction after delay has passed");

            return(data);
        }
Example #27
0
        private void ProcessDataRequest(DataRequest dataRequest, IClient client)
        {
            // the collection name is case insensitive
            var key = DataStores.Keys.FirstOrDefault(k => dataRequest.CollectionName.ToLower() == k.ToLower());

            DataStore dataStore = null;

            if (key != null)
            {
                dataStore = DataStores.TryGetValue(key);
            }
            else
            {
                // for now there is one special table containing the activity log. It is always non persistent and it has an LRU eviction policy

                if (dataRequest.CollectionName.ToLower() == "@activity")
                {
                    dataStore = _serviceContainer.Log.ActivityTable;
                }
            }


            if (dataStore == null)
            {
                throw new NotSupportedException("Unknown collection : " + dataRequest.CollectionName);
            }


            Dbg.Trace($"begin processing {dataRequest.AccessType} request on server {ShardIndex}");

            var lockManager = _serviceContainer.LockManager;

            if (dataRequest.AccessType == DataAccessType.Write)
            {
                if (dataRequest is DomainDeclarationRequest)
                {
                    if (PersistenceEngine != null)
                    {
                        throw new NotSupportedException(
                                  "Domain declaration can only be used in cache mode (without persistence)");
                    }
                }

                if (dataRequest is EvictionSetupRequest)
                {
                    if (PersistenceEngine != null)
                    {
                        throw new NotSupportedException(
                                  "Eviction can only be used in cache mode (without persistence)");
                    }
                }


                lockManager.DoWithWriteLock(() =>
                {
                    if (dataRequest is RemoveManyRequest removeManyRequest)
                    {
                        var mgr = new DeleteManager(dataStore, PersistenceEngine);

                        mgr.ProcessRequest(removeManyRequest, client);
                    }
                    else if (dataRequest is PutRequest putRequest)
                    {
                        var mgr = new PutManager(PersistenceEngine, _serviceContainer.FeedSessionManager, dataStore, _serviceContainer.Log);

                        mgr.ProcessRequest(putRequest, client);
                    }
                    else if (dataRequest is DomainDeclarationRequest domainDeclarationRequest)
                    {
                        var mgr = new CacheOnlyManager(dataStore);

                        mgr.ProcessRequest(domainDeclarationRequest, client);
                    }

                    else if (dataRequest is EvictionSetupRequest evictionSetupRequest)
                    {
                        var mgr = new CacheOnlyManager(dataStore);

                        mgr.ProcessRequest(evictionSetupRequest, client);
                    }
                }, dataRequest.CollectionName);
            }
            else
            {
                if (dataRequest.SessionId != default)// request inside a consistent read context
                {
                    if (lockManager.CheckLock(dataRequest.SessionId, false, dataRequest.CollectionName))
                    {
                        if (dataRequest is GetRequest getRequest)
                        {
                            new QueryManager(dataStore, _serviceContainer.Log).ProcessRequest(getRequest, client);
                        }
                        else if (dataRequest is EvalRequest evalRequest)
                        {
                            new QueryManager(dataStore).ProcessRequest(evalRequest, client);
                        }
                        else if (dataRequest is PivotRequest pivotRequest)
                        {
                            new QueryManager(dataStore).ProcessRequest(pivotRequest, client);
                        }
                    }
                    else
                    {
                        throw new NotSupportedException("Data request with session received but no session is active");
                    }
                }
                else // simple request
                {
                    lockManager.DoWithReadLock(() =>
                    {
                        if (dataRequest is GetRequest getRequest)
                        {
                            new QueryManager(dataStore, _serviceContainer.Log).ProcessRequest(getRequest, client);
                        }
                        else if (dataRequest is EvalRequest evalRequest)
                        {
                            new QueryManager(dataStore).ProcessRequest(evalRequest, client);
                        }
                        else if (dataRequest is PivotRequest pivotRequest)
                        {
                            new QueryManager(dataStore).ProcessRequest(pivotRequest, client);
                        }
                    }, dataRequest.CollectionName);
                }
            }

            Dbg.Trace($"end processing {dataRequest.AccessType} request on server {ShardIndex}");
        }
Example #28
0
        private void StartProcessingTransactions()
        {
            _shouldContinue = true;
            _singleConsumer = new Thread(() =>
            {
                while (_shouldContinue)
                {
                    try
                    {
                        // this call is blocking if nothing to process
                        var persistentTransaction = TransactionLog.StartProcessing();

                        if (persistentTransaction != null &&
                            persistentTransaction.TransactionStatus != TransactionStatus.Canceled)
                        {
                            var data        = persistentTransaction.Data;
                            var transaction =
                                SerializationHelper.ObjectFromBytes <DurableTransaction>(data,
                                                                                         SerializationMode.ProtocolBuffers,
                                                                                         false);

                            if (transaction is MixedDurableTransaction mixedTransaction)
                            {
                                foreach (var item in mixedTransaction.ItemsToPut)
                                {
                                    var itemFromMemory = GetItemWithTokenizedFullText(item);

                                    var itemData =
                                        SerializationHelper.ObjectToBytes(itemFromMemory, SerializationMode.ProtocolBuffers,
                                                                          false);

                                    Dbg.Trace(
                                        $"storing persistent block for object {item} transaction={persistentTransaction.Id}");
                                    _storage.StoreBlock(itemData, item.GlobalKey,
                                                        unchecked ((int)persistentTransaction.Id));
                                }

                                foreach (var item in mixedTransaction.ItemsToDelete)
                                {
                                    Dbg.Trace($"deleting persistent block {persistentTransaction.Id}");
                                    _storage.DeleteBlock(item.GlobalKey, unchecked ((int)persistentTransaction.Id));
                                }
                            }

                            if (transaction is PutDurableTransaction putTransaction)
                            {
                                foreach (var item in putTransaction.Items)
                                {
                                    var itemFromMemory = GetItemWithTokenizedFullText(item);

                                    var itemData =
                                        SerializationHelper.ObjectToBytes(itemFromMemory, SerializationMode.ProtocolBuffers,
                                                                          false);

                                    Dbg.Trace(
                                        $"storing persistent block for object {item} transaction={persistentTransaction.Id}");
                                    _storage.StoreBlock(itemData, item.GlobalKey,
                                                        unchecked ((int)persistentTransaction.Id));
                                }
                            }

                            if (transaction is DeleteDurableTransaction deleteTransaction)
                            {
                                foreach (var item in deleteTransaction.ItemsToDelete)
                                {
                                    Dbg.Trace($"deleting persistent block {persistentTransaction.Id}");
                                    _storage.DeleteBlock(item.GlobalKey, unchecked ((int)persistentTransaction.Id));
                                }
                            }

                            TransactionLog.EndProcessing(persistentTransaction);
                        }
                        else
                        {
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        Dbg.Trace(e.Message);
                        //TODO add proper logging
                    }
                }
            });

            _singleConsumer.Start();
        }
Example #29
0
    IEnumerator LoadSceneRoutine(string scene)
    {
        Dbg.LogRelease(this, "APP: Will load scene {0}", scene);

        OnSceneWillUnload();

        isLoading = true;

        BeginLoadingScope("Loading load scene");
        SceneManager.LoadScene(loadingSceneName);

        // The actual loading starts 'next frame'
        yield return(null);

        EndLoadingScope();

        Dbg.LogWarnReleaseIf(
            Game.callbackCounter != 0,
            this,
            "APP: Game had {0} callbacks still registered. These will be cleared, but should be properly taken care of.",
            Game.callbackCounter
            );

        Game.ClearCallbacks();

        BeginLoadingScope("Unloading unused assets");
        loadOperation = Resources.UnloadUnusedAssets();
        loadMessage   = "Unloading Unused Assets";
        yield return(loadOperation);

        loadOperation = null;
        EndLoadingScope();

        // Wait if something wants to fade in or such
        // before loading starts
        while (delaySceneLoad)
        {
            yield return(null);
        }

        loadMessage   = scene;
        loadOperation = SceneManager.LoadSceneAsync(scene);

        if (loadOperation == null)
        {
            loadSceneRoutine = null;
            loadOperation    = null;

            Dbg.LogErrorRelease(this, "APP: Failed to start loading {0}, was probably not added to settings", scene);
            yield break;
        }

        loadOperation.allowSceneActivation = false;

        BeginLoadingScope("Loading scene");
        // AsyncOp will never return isDone if
        // allowSceneActivation is false, so
        // wait until 0.9
        while (loadOperation.progress < 0.9f)
        {
            yield return(null);
        }
        EndLoadingScope();

        // Give other stuff a frame to delay
        // the scene
        yield return(null);

        while (delayActivatingScene)
        {
            yield return(null);
        }

        loadOperation.allowSceneActivation = true;

        // Now wait until isDone is true
        while (!loadOperation.isDone)
        {
            yield return(null);
        }

        // Let scene load method piggyback on this
        // coroutine but still reset variables,
        // a new scene load may be initiated from
        // OnSceneLoaded
        isLoading        = false;
        loadSceneRoutine = null;
        loadOperation    = null;

        OnSceneLoaded();
    }
Example #30
0
    IEnumerator OnSceneLoadedRoutine()
    {
        Dbg.LogRelease(this, "APP: Scene loaded");

        while (!readyForSceneLoad)
        {
            yield return(null);
        }

        Scene activeScene = SceneManager.GetActiveScene();

        if (activeScene.name == splashSceneName)
        {
            Dbg.LogRelease(this, "APP: Scene was splash");

            // Null here already because after this we're done
            setupRoutine = null;

            for (int buildIndex = 0; buildIndex < SceneManager.sceneCountInBuildSettings; ++buildIndex)
            {
                string sceneName      = Path.GetFileNameWithoutExtension(SceneUtility.GetScenePathByBuildIndex(buildIndex));
                bool   validSceneName =
                    !string.IsNullOrEmpty(sceneName) &&
                    sceneName != loadingSceneName &&
                    sceneName != splashSceneName
                ;
                if (validSceneName)
                {
                    Dbg.LogRelease(this, "APP: Found first scene \"{0}\"", sceneName);
                    LoadScene(sceneName);
                    yield break;
                }
            }

            Dbg.LogErrorRelease(this, "APP: Did not find a first scene to load");
            yield break;
        }

        Dbg.LogRelease(this, "APP: Disabling Gravity");
        Vector3 gravityToRestore = Physics.gravity;

        Physics.gravity = Vector3.zero;

        AppState appState = FindAndInitializeAppState();

        if (appState != null)
        {
            while (!appState.readyForSetup)
            {
                yield return(null);
            }

            currentAppState = appState;

            try
            {
                currentAppState.AtSetup();
            }
            catch (Exception exc)
            {
                Dbg.LogExcRelease(exc);
                Dbg.LogErrorRelease(this, "APP: State setup failed");

                UE.Debug.Break();
            }
        }

        Dbg.LogRelease(this, "APP: Restoring Gravity");
        Physics.gravity = gravityToRestore;
        setupRoutine    = null;
    }
Example #31
0
 /// <summary>
 /// Called to signal that the raw connection got established but before the client can call operation on the server.
 /// </summary>
 /// <remarks>
 /// After the (low level transport) connection is established, the client will automatically send
 /// the Authentification operation, which needs to get a response before the client can call other operations.
 ///
 /// Your logic should wait for either: OnRegionListReceived() or OnConnectedToMaster().
 ///
 /// This callback is useful to detect if the server can be reached at all (technically).
 /// Most often, it's enough to implement OnDisconnected().
 ///
 /// This is not called for transitions from the masterserver to game servers.
 /// </remarks>
 /// <param name="cause"></param>
 public override void OnDisconnected(DisconnectCause cause)
 {
     Dbg.LogW($"ConnectRule: OnDisconnected() was called by PUN with reason {cause.ToString()}");
 }