Пример #1
0
        /// <summary>
        /// Uses the snapshot of current nodes to start gossiping with
        /// </summary>
        private void SendStateUpdate()
        {
            _logger.Debug("{Name} is sending new gossip message", _name);

            // If there are actors still to tell..
            if (_actorsToTell.Any())
            {
                // Randomly select an actor to tell...
                // ...and remove it from the set and add it to "told"
                _actorsToTell = _actorsToTell.RemoveAtRandom(out ActorPath actor);
                _actorsTold.Add(actor);
            }

            // Create status update
            var data = new StateUpdate(_currentNodes, _gossipState);

            // Send the message to all told actors
            foreach (var item in _actorsTold)
            {
                Context.ActorSelection(item).Tell(data);
            }
        }
Пример #2
0
    public void cambiarEstado(EstadoArmada nuevoEstado)
    {
        switch (nuevoEstado)
        {
        case EstadoArmada.PATRULLANDO:
            stateUpdate = updatePatrullando;
            break;

        case EstadoArmada.PERSIGUE:
            stateUpdate = updatePersiguiendo;
            break;

        case EstadoArmada.ATRAPAR:
            stateUpdate = updateAtraparPirata;
            break;

        case EstadoArmada.ACOMPANA_COMERCIANTE:
            stateUpdate = updateAcompanando;
            break;
        }
        estadoActual = nuevoEstado;
    }
Пример #3
0
        private bool CompareStateUpdates(StateUpdate desObj, StateUpdateObject sup)
        {
            var passed = true;

            passed &= desObj.Delete(0) == sup.delete[0];
            passed &= desObj.Create(0).Value.Id == sup.create[0].id && desObj.Create(0).Value.Owner == sup.create[0].owner &&
                      new Vector3(desObj.Create(0).Value.Position.Value.X, desObj.Create(0).Value.Position.Value.Y,
                                  desObj.Create(0).Value.Position.Value.Z) ==
                      sup.create[0].position && new Vector3(desObj.Create(0).Value.LookDirection.Value.X,
                                                            desObj.Create(0).Value.LookDirection.Value.Y,
                                                            desObj.Create(0).Value.LookDirection.Value.Z) ==
                      sup.create[0].lookDirection;

            passed &= desObj.Update(0).Value.Id == sup.update[0].id && desObj.Update(0).Value.Owner == sup.update[0].owner &&
                      new Vector3(desObj.Update(0).Value.Position.Value.X, desObj.Update(0).Value.Position.Value.Y,
                                  desObj.Update(0).Value.Position.Value.Z) ==
                      sup.update[0].position && new Vector3(desObj.Update(0).Value.LookDirection.Value.X,
                                                            desObj.Update(0).Value.LookDirection.Value.Y,
                                                            desObj.Update(0).Value.LookDirection.Value.Z) ==
                      sup.update[0].lookDirection;


            return(passed);
        }
Пример #4
0
        public void TestStateUpdate()
        {
            var sup     = new StateUpdateObject();
            var created = new RoomObjectObj
            {
                disposable    = true,
                id            = 27,
                isHidden      = false,
                lookDirection = Vector3.forward,
                owner         = "test",
                position      = Vector3.one,
                prefab        = "a test thing"
            };
            var updated = new RoomObjectObj
            {
                disposable    = false,
                id            = 23,
                isHidden      = true,
                lookDirection = Vector3.back,
                owner         = "test",
                position      = Vector3.down,
                prefab        = ""
            };
            var deleted = 0;

            var TestAnnotation = new AnnotationObject
            {
                isValid   = true,
                lineId    = "testLine",
                positions = new[] { Vector3.one },
                userId    = "testUser"
            };

            TargetPlacementObject poi = new TargetPlacementObject
            {
                id       = 0,
                isValid  = true,
                name     = "testPoi",
                position = Vector3.one
            };

            var sitedrive = "SomeSiteDrive";

            var TestSUP = new StateUpdateObject
            {
                poiPlacementObject = poi,
                annotationObjects  = new List <AnnotationObject>()
                {
                    TestAnnotation
                },
                create = new List <RoomObjectObj>()
                {
                    created
                },
                update = new List <RoomObjectObj>()
                {
                    updated
                },
                delete = new List <int>()
                {
                    deleted
                },
                siteDrive = sitedrive
            };

            var fbb    = new FlatBufferBuilder(1024);
            var offset = TestSUP.ToBuffer(fbb);

            fbb.Finish(offset.Value);
            var bArray = fbb.SizedByteArray();
            var bb     = new ByteBuffer(bArray);
            var desObj = StateUpdate.GetRootAsStateUpdate(bb);
            var passed = CompareStateUpdates(desObj, TestSUP);

            print("State Update : " + (passed ? "Passed" : "Failed"));
        }
Пример #5
0
 public virtual void OnStateChange(StateUpdate e)
 {
     StateChange?.Invoke(this, e);
 }
Пример #6
0
        public Payload ProcessMsgRequest(Payload rqMsg)
        {
            Payload respMsg = new Payload();

            respMsg.id = rqMsg.id;
            StateUpdate sU = new StateUpdate();

            switch (rqMsg.msg)
            {
            case "INITIALIZE":
                if (Board == null)
                {
                    Board = new Board();
                }
                Board.Initialize();
                CurrentPlayer = PlayerType.Player1;
                PlayerMove    = MoveType.STARTING_MOVE;

                respMsg.msg = rqMsg.msg;

                sU.heading   = "Player 1";
                sU.message   = "Awaiting Player 1's Move";
                respMsg.body = sU;


                break;

            case "NODE_CLICKED":

                Point p = rqMsg.body as Point;
                LogState("NODE_CLICKED Preprocess", p);
                switch (PlayerMove)
                {
                case MoveType.STARTING_MOVE:
                    if (CanMove(p, Board.StartPoint, PlayerMove))
                    {
                        LogState("Starting Move", p);
                        respMsg.msg = respVals[respType.VALID_START_NODE];

                        // show which player should complete the next move
                        sU.heading   = CurrentPlayer == PlayerType.Player1 ? "Player 1" : "Player 2";
                        sU.message   = "Select a second node to complete the line";
                        respMsg.body = sU;
                        Move(p);                                          //state changes to ending move no change to player
                        LogState("NODE_CLICKED postprocess", p);
                    }
                    else
                    {
                        respMsg.msg = respVals[respType.INVALID_START_NODE];

                        // show which player should complete the next move
                        sU.heading   = CurrentPlayer == PlayerType.Player1 ? "Player 1" : "Player 2";
                        sU.message   = "Not a valid starting position.";
                        respMsg.body = sU;
                    }
                    break;

                case MoveType.ENDING_MOVE:
                    if (CanMove(p, Board.StartPoint, PlayerMove))
                    {
                        sU.newLine   = new Line(Board.StartPoint, p);
                        respMsg.body = sU;

                        Move(p);                                         //  state to next player and move to starting
                        if (DoesPossibleNextMoveExist())
                        {
                            respMsg.msg  = respVals[respType.VALID_END_NODE];
                            sU.heading   = CurrentPlayer != PlayerType.Player1 ? "Player 2" : "Player 1";
                            sU.message   = "Awaiting Move";
                            respMsg.body = sU;
                        }
                        else
                        {
                            respMsg.msg  = respVals[respType.GAME_OVER];
                            sU.message   = "Player Wins";
                            sU.heading   = CurrentPlayer != PlayerType.Player1 ? "Player 2 Wins" : "Player 1 Wins";
                            respMsg.body = sU;
                        }

                        LogState("NODE_CLICKED postprocess", p);
                    }
                    else
                    {
                        respMsg.msg  = respVals[respType.INVALID_END_NODE];
                        sU.message   = "Invalid move!";
                        sU.heading   = sU.heading = CurrentPlayer == PlayerType.Player1 ? "Player 1" : "Player 2";
                        respMsg.body = sU;
                        //reset state to await first move
                        ResetState();                                          // reverses attempt
                        PlayerMove = MoveType.STARTING_MOVE;
                    }
                    break;
                }
                break;


            case "ERROR":
            default:
                break;
            }

            return(respMsg);
        }
Пример #7
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    void OnNextMission () {
        State = null;
        SendMessage("OnMissionLevelUp");
        StartCoroutine(this.StartMission());
    }
Пример #8
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    void UpdateMissionReport () {
        float delta = Time.realtimeSinceStartup - missionReportStartTime;
        if ( delta >= MissionReportForSeconds ) {
            State = WaitForUserInput;
        }

        // we use 0.5 seconds to refresh
        float ratio = Mathf.Min( 1.0f, delta/0.5f );

        // report list
        this.txtZombieKilled.Text = "zombie killed: " + (int)(this.CurrentCount * ratio);
        this.txtTime.Text = "time: " 
            + string.Format( "{0:0}", (timeMissionFinished - timeMissionStart) * ratio )
            + " sec";
        this.txtDamageTaken.Text = "damage taken: " 
            + string.Format( "{0:0}", this.DamageTaken * ratio );
        this.txtBulletUsed.Text = "bullet used: " + (int)(this.BulletUsed * ratio);
        this.txtPerfectReloads.Text = "perfect reloads: " + (int)(this.PerfectReloadCount * ratio);
        // TODO { 
        // this.txtExpBounus.Text = "EXP Bounus: " + ;
        // } TODO end 
    }
Пример #9
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

	public override IEnumerator StartMission () {
        ResetMission();
        Game.PlayAsGod(false);
        StartCoroutine(Game.Pause());

        StartScene.transform.position = startSceneInitPos; 
        StartScene.SetActiveRecursively(true);
        int levelCount = this.GetComponent<MissionLevels>().CurrentLevel();
        txtStage.Text = "stage " + levelCount;
        txtZombieToKill.Text = "kill " + this.CompleteCount + " zombies !!!";

        Vector3 from = startSceneInitPos + new Vector3( -1000.0f, 0.0f, 0.0f ); 
        Vector3 to = startSceneInitPos + new Vector3( 1000.0f, 0.0f, 0.0f ); 

        iTween.MoveFrom ( this.StartScene, iTween.Hash( "position", from, 
                                                        "time", 1.0f,
                                                        "easetype", iTween.EaseType.easeOutBack, 
                                                        "ignoretimescale", true
                                                      ) );
        yield return StartCoroutine ( CoroutineHelper.WaitForRealSeconds(this.StartSceneShowForSeconds+1.0f) ); 
        iTween.MoveTo ( this.StartScene, iTween.Hash( "position", to, 
                                                      "time", 1.0f,
                                                      "easetype", iTween.EaseType.easeOutBack, 
                                                      "ignoretimescale", true,
                                                      "oncomplete", "HideStartScene",
                                                      "oncompletetarget", this.gameObject
                                                    ) );

        yield return StartCoroutine(Game.Run());

        this.zombieFace.gameObject.SetActiveRecursively(true);
        this.txtDeadZombeCounter.gameObject.SetActiveRecursively(true);
        this.txtDeadZombeCounter.Text = "dead zombies: " + this.CurrentCount + "/" + this.CompleteCount;
        iTween.ScaleFrom ( this.zombieFace.gameObject, new Vector3( 2.0f, 2.0f, 2.0f ), 0.6f ); 
        iTween.ScaleFrom ( this.txtDeadZombeCounter.gameObject, new Vector3( 2.0f, 2.0f, 2.0f ), 0.6f ); 

        timeMissionStart = Time.time;
        State = UpdateMission;
    }
Пример #10
0
        /// <summary>
        /// Updates the local copy of the global state via server delta
        /// </summary>
        /// <param name="serverUpdate">changes to the global state since last server tick</param>
        private void UpdateLocalState(StateUpdate serverUpdate)
        {
            RoomStateGen newRoomState = new RoomStateGen(globalState);

            #region properties update

            bool propsChanged  = false;
            bool isSceneUpdate = false;
            if (!string.IsNullOrEmpty(serverUpdate.SiteDrive))
            {
                propsChanged  = true;
                isSceneUpdate = true;
            }
            else
            {
                if (serverUpdate.AnnotationsLength > 0)
                {
                    propsChanged = true;
                }
                if (serverUpdate.Poi.HasValue)
                {
                    propsChanged = true;
                }
            }
            if (propsChanged)
            {
                if (isSceneUpdate)
                {
                    if (OnPropertiesChanged != null)
                    {
                        OnPropertiesChanged.Invoke(this, serverUpdate);
                    }
                }
                else
                {
                    serverUpdate.Debounce(this, props =>
                    {
                        if (OnPropertiesChanged != null)
                        {
                            OnPropertiesChanged.Invoke(this, props);
                        }
                    }, isSceneUpdate);
                }
            }

            #endregion

            if (serverUpdate.DeleteLength > 0) //delete these object ids from the global state
            {
                print("Deleting " + serverUpdate.DeleteLength + " objects");
                for (int i = 0; i < serverUpdate.DeleteLength; i++)
                {
                    if (newRoomState.objects.All(tr => tr.id != serverUpdate.Delete(i)))
                    {
                        print("object to delete not found in global state " + serverUpdate.Delete(i));
                        continue;
                    }
                    newRoomState.objects.Remove(globalState.objects.Single(o => o.id == serverUpdate.Delete(i)));
                    if (trackers.ContainsKey(serverUpdate.Delete(i)) && trackers[serverUpdate.Delete(i)] != null)
                    {
                        Destroy(((MonoBehaviour)trackers[serverUpdate.Delete(i)]).gameObject);
                    }
                    else
                    {
                        print("Could not find game object to destroy" + serverUpdate.Delete(i));
                    }
                }
            }
            if (serverUpdate.CreateLength > 0) //create these objects and add them to the global state
            {
                for (int i = 0; i < serverUpdate.CreateLength; i++)
                {
                    if (!serverUpdate.Create(i).HasValue)
                    {
                        print("Malformed create message");
                        continue;
                    }
                    if (!trackers.ContainsKey(serverUpdate.Create(i).Value.Id))
                    {
                        CreateObject(serverUpdate.Create(i).Value, newRoomState);

                        //if (newRoomState.objects.Contains(serverUpdate.Create(i).Value))
                        //continue;
                    }
                    else
                    {
                        print("Object " + serverUpdate.Create(i).Value.Id + " already exists");
                    }
                    //else
                    //{
                    //  if (newRoomState.objects.Any(tr => tr.id == serverUpdate.Create(i).Value.Id))
                    //    newRoomState.objects.Remove(newRoomState.objects.Single(o => o.id == serverUpdate.Create(i).Value.Id));
                    //  var oldObj = (MonoBehaviour) trackers[serverUpdate.Create(i).Value.Id];
                    //  if (oldObj) Destroy(oldObj.gameObject);
                    //  trackers.Remove(serverUpdate.Create(i).Value.Id);
                    //}
                    //CreateObject(serverUpdate.Create(i).Value, newRoomState);
                }
            }
            if (serverUpdate.UpdateLength > 0)
            {
                for (int i = 0; i < serverUpdate.UpdateLength; i++)
                {
                    if (!serverUpdate.Update(i).HasValue)
                    {
                        continue;
                    }
                    if (!trackers.ContainsKey(serverUpdate.Update(i).Value.Id))
                    {
                        Debug.Log("Object created from update. please use the create function instead");
                        //CreateObject(serverUpdate.Update(i).Value, newRoomState);
                        continue;
                    }
                    trackers[serverUpdate.Update(i).Value.Id].UpdateFromRoomObject(serverUpdate.Update(i).Value);
                }
            }
            oldStateGen = new RoomStateGen(globalState);
            globalState = newRoomState;
        }
Пример #11
0
 public async Task Post([FromBody] StateUpdate update)
 {
     await this.subscriptionHandler.PostUpdate(update);
 }
Пример #12
0
 public StateUpdateReply(StateUpdate data, IEnumerable <ActorPath> nodes, TState state) : this(data.Id, nodes, state)
 {
 }
Пример #13
0
 public void MapState(StateEnter stateEnter, StateUpdate stateUpdate)
 {
     MapState(stateEnter, stateUpdate, null);
 }
Пример #14
0
        /// <summary>
        /// Updates the local copy of the global state via server delta
        /// </summary>
        /// <param name="serverUpdate">changes to the global state since last server tick</param>
        private void UpdateLocalState(StateUpdate serverUpdate)
        {
            RoomStateGen newRoomState = new RoomStateGen(globalState);

            #region properties update

            bool propsChanged = false;
            if (propsChanged)
            {
            }

            #endregion

            if (serverUpdate.DeleteLength > 0) //delete these object ids from the global state
            {
                print("Deleting " + serverUpdate.DeleteLength + " objects");
                for (int i = 0; i < serverUpdate.DeleteLength; i++)
                {
                    if (newRoomState.objects.All(tr => tr.id != serverUpdate.Delete(i)))
                    {
                        print("object to delete not found in global state " + serverUpdate.Delete(i));
                        continue;
                    }
                    newRoomState.objects.Remove(globalState.objects.Single(o => o.id == serverUpdate.Delete(i)));
                    if (trackers.ContainsKey(serverUpdate.Delete(i)) && trackers[serverUpdate.Delete(i)] != null)
                    {
                        Destroy(((MonoBehaviour)trackers[serverUpdate.Delete(i)]).gameObject);
                    }
                    else
                    {
                        print("Could not find game object to destroy" + serverUpdate.Delete(i));
                    }
                }
            }
            if (serverUpdate.CreateLength > 0) //create these objects and add them to the global state
            {
                for (int i = 0; i < serverUpdate.CreateLength; i++)
                {
                    if (!serverUpdate.Create(i).HasValue)
                    {
                        print("Malformed create message");
                        continue;
                    }
                    if (!trackers.ContainsKey(serverUpdate.Create(i).Value.Id))
                    {
                        CreateObject(serverUpdate.Create(i).Value, newRoomState);

                        //if (newRoomState.objects.Contains(serverUpdate.Create(i).Value))
                        //continue;
                    }
                    else
                    {
                        print("Object " + serverUpdate.Create(i).Value.Id + " already exists");
                    }
                }
            }
            if (serverUpdate.UpdateLength > 0)
            {
                for (int i = 0; i < serverUpdate.UpdateLength; i++)
                {
                    if (!serverUpdate.Update(i).HasValue)
                    {
                        continue;
                    }
                    if (!trackers.ContainsKey(serverUpdate.Update(i).Value.Id))
                    {
                        Debug.Log("Object created from update. please use the create function instead");
                        //CreateObject(serverUpdate.Update(i).Value, newRoomState);
                        continue;
                    }
                    trackers[serverUpdate.Update(i).Value.Id].UpdateFromRoomObject(serverUpdate.Update(i).Value);
                }
            }
            oldStateGen = new RoomStateGen(globalState);
            globalState = newRoomState;
        }
Пример #15
0
 public void AddState(string stateName, StateUpdate updateFunction)
 {
     StateFunctions.Add(stateName, updateFunction);
 }
Пример #16
0
 /// <inheritdoc />
 public byte[] GetHash(StateUpdate stateUpdate, in long number)
Пример #17
0
        public void UpdateState(byte[] data)
        {
            BongoData update = new BongoData(data);

            if (!update.Equals(previousBongo))
            {
                StateUpdate?.Invoke(update);
            }

            if (update.micLevel != previousBongo.micLevel)
            {
                MicUpdate?.Invoke(update.micLevel);
            }

            if (update.botLeft && !previousBongo.botLeft)
            {
                BotLeftPressed?.Invoke();
            }
            if (update.botRight && !previousBongo.botRight)
            {
                BotRightPressed?.Invoke();
            }
            if (update.topLeft && !previousBongo.topLeft)
            {
                TopLeftPressed?.Invoke();
            }
            if (update.topRight && !previousBongo.topRight)
            {
                TopRightPressed?.Invoke();
            }
            if (update.start && !previousBongo.start)
            {
                StartPressed?.Invoke();
            }
            if (update.micLevel >= micThreshold && previousBongo.micLevel < micThreshold)
            {
                MicStarted?.Invoke();
            }

            if (update.botLeft && previousBongo.botLeft)
            {
                BotLeftHeld?.Invoke();
            }
            if (update.botRight && previousBongo.botRight)
            {
                BotRightHeld?.Invoke();
            }
            if (update.topLeft && previousBongo.topLeft)
            {
                TopLeftHeld?.Invoke();
            }
            if (update.topRight && previousBongo.topRight)
            {
                TopRightHeld?.Invoke();
            }
            if (update.start && previousBongo.start)
            {
                StartHeld?.Invoke();
            }
            if (update.micLevel >= micThreshold && previousBongo.micLevel >= micThreshold)
            {
                MicHeld?.Invoke();
            }

            if (!update.botLeft && previousBongo.botLeft)
            {
                BotLeftReleased?.Invoke();
            }
            if (!update.botRight && previousBongo.botRight)
            {
                BotRightReleased?.Invoke();
            }
            if (!update.topLeft && previousBongo.topLeft)
            {
                TopLeftReleased?.Invoke();
            }
            if (!update.topRight && previousBongo.topRight)
            {
                TopRightReleased?.Invoke();
            }
            if (!update.start && previousBongo.start)
            {
                StartReleased?.Invoke();
            }
            if (update.micLevel < micThreshold && previousBongo.micLevel >= micThreshold)
            {
                MicReleased?.Invoke();
            }

            //Console.WriteLine(update.micLevel);

            previousBongo = update;
        }
Пример #18
0
        private void MessageHandler(object sender, MessageEventArgs e)
        {
            var bb = new ByteBuffer(e.RawData);

            ServerMessage msg = ServerMessage.GetRootAsServerMessage(bb);

            switch (msg.Type)
            {
            case msgType.RoomStateUpdate:
                //handle message
                if (msg.Data <StateUpdate>() == null)
                {
                    print("empty state update. this should not happen");
                    return;
                }
                StateUpdate?stateUpdate = msg.Data <StateUpdate>();
                if (stateUpdate != null)
                {
                    StateUpdate sup =
                        stateUpdate.Value;
                    UpdateLocalState(sup);
                }
                break;

            case msgType.SocketReady:
                print("connected to server");
                StringData?stringData = msg.Data <StringData>();
                if (stringData != null)
                {
                    OnConnectedArgs connectedEventArgs = new OnConnectedArgs
                    {
                        sid = stringData.Value.Data,
                    };
                    NeuraCore.Instance.sid = connectedEventArgs.sid;
                }
                if (OnConnected != null)
                {
                    OnConnected.Invoke(this, new EventArgs());
                }
                break;

            case msgType.SocketRoomJoined:
            {
                print("Joined room ");
                inRoom = true;
                UsersInRoom.Add(localUserName);
                NeuraCore.Instance.connectionState = ConnectionState.Connected;
                if (msg.DataType != Transport.FlatBuffers.msg.StateUpdate)
                {
                    return;
                }
                if (msg.Data <StateUpdate>().HasValue)
                {
                    var initStateSUP = msg.Data <StateUpdate>().Value;
                    UpdateLocalState(initStateSUP);
                }
                if (OnRoomJoined != null)
                {
                    OnRoomJoined.Invoke(this, RoomName);
                }
            }
            break;

            case msgType.RoomCreated:
                StringData?createMsg = msg.Data <StringData>();
                if (createMsg != null)
                {
                    //var rmName = createMsg.Value.Data;
                    //RoomName = rmName;
                    print("room " + RoomName + " has been created");
                    if (OnRoomCreated != null)
                    {
                        OnRoomCreated.Invoke(this, RoomName);
                    }
                    if (string.IsNullOrEmpty((globalState ?? (globalState = new RoomStateGen())).siteDrive))
                    {
                        //Handle things like critical room state here to make sure that the initial state sent has the required information
                        //For onsight the site drive is of critical importance so we are setting it below
                        //globalState.siteDrive = string.IsNullOrEmpty(requestedSiteDrive)
                        //    ? MultiUserConnectionManager.Instance.CurrentSiteDriveJSON
                        //    : requestedSiteDrive;
                    }
                    Debug.Assert(!string.IsNullOrEmpty(globalState.siteDrive));

                    NeuraCore.Instance.SendInitialState(ServerMessageFactory.BuildMessage(globalState));
                }
                break;

            case msgType.RoomUserOnjoined:
                StringData?joinedMsg = msg.Data <StringData>();
                if (joinedMsg != null)
                {
                    var user = joinedMsg.Value.Data;
                    print(user + " has joined the room");
                    UsersInRoom.Add(user);
                    if (OnUserJoined != null)
                    {
                        OnUserJoined.Invoke(this, new UserJoinedEventArgs
                        {
                            username = user
                        });
                    }
                }
                break;

            case msgType.RoomUserOnLeft:
                StringData?leftMsg = msg.Data <StringData>();
                if (leftMsg != null)
                {
                    var user = leftMsg.Value.Data;
                    print(user + " has left the room");
                    if (UsersInRoom.Contains(user))
                    {
                        UsersInRoom.Remove(user);
                    }
                    if (OnUserLeft != null)
                    {
                        OnUserLeft.Invoke(this, new UserLeftEventArgs
                        {
                            username = user
                        });
                    }
                }
                break;
            }
        }
Пример #19
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    void Start () {
        // hide active reload bar at the beginning
        activeReloadBar.SetColor( new Color( 1.0f, 1.0f, 1.0f, 0.0f ) );
        activeReloadFloat.SetColor( new Color( 1.0f, 1.0f, 1.0f, 0.0f ) );
        activeReloadZone.SetColor( new Color( 1.0f, 1.0f, 1.0f, 0.0f ) );

        //
        this.hint_lowAmmo.SetActiveRecursively(false);
        this.hint_reloadBin.SetActiveRecursively(false);
        this.hint_tapAgain.SetActiveRecursively(false);

        //
        this.ActiveAimingZone(false);
        this.ActiveMovingZone(false);
        this.ActiveMeleeButton(false);

        // init reload button state
        DisableReloadButton();
        ReloadButtonState = UpdateReloadDeactive;
    }
Пример #20
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    void UpdateMission () {
        // don't do anything if game over
        if ( Game.IsGameOver() )
            return;

        if ( this.CurrentCount >= this.CompleteCount ) {
            State = null;
            StartCoroutine(OnMissionComplete());
        }
    }
Пример #21
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    public IEnumerator ShowControls ( bool _show, float _sec ) {
        this.showControls = _show;
        if ( _show ) {
            yield return StartCoroutine ( CoroutineHelper.WaitForRealSeconds(0.1f) ); 

            // process fade in
            for ( int i = 0; i < ShowHideControls.Length; ++i ) {
                iTween.MoveTo( ShowHideControls[i],
                               iTween.Hash( "position", showHideInitPos[i],
                                            "time", _sec, 
                                            "isLocal", true,
                                            "easetype", iTween.EaseType.easeOutBack,
                                            "ignoretimescale", true
                                          ) );
            }
        }
        else {
            // reset the button status
            iTween.Stop(this.gameObject, true );

            this.girlFace.transform.position = this.initGirlTrans.position;
            this.girlFace.transform.rotation = this.initGirlTrans.rotation;
            this.boyFace.transform.position = this.initBoyTrans.position;
            this.boyFace.transform.rotation = this.initBoyTrans.rotation;

            this.hint_lowAmmo.SetActiveRecursively(false);
            this.hint_reloadBin.SetActiveRecursively(false);
            this.hint_tapAgain.SetActiveRecursively(false);
            this.ActiveAimingZone(false);
            this.ActiveMovingZone(false);
            this.ActiveMeleeButton(false);

            // hide active reload bar at the beginning
            activeReloadBar.SetColor( new Color( 1.0f, 1.0f, 1.0f, 0.0f ) );
            activeReloadFloat.SetColor( new Color( 1.0f, 1.0f, 1.0f, 0.0f ) );
            activeReloadZone.SetColor( new Color( 1.0f, 1.0f, 1.0f, 0.0f ) );

            // init reload button state
            DisableReloadButton();
            ReloadButtonState = UpdateReloadDeactive;
            yield return StartCoroutine ( CoroutineHelper.WaitForRealSeconds(0.2f) ); 

            // process fade out
            for ( int i = 0; i < ShowHideControls.Length; ++i ) {
                Vector3 pos = showHideInitPos[i];
                pos = new Vector3 ( pos.x + pos.normalized.x * 400.0f,
                                    pos.y + pos.normalized.y * 400.0f,
                                    pos.z );
                iTween.MoveTo( ShowHideControls[i],
                               iTween.Hash( "position", pos,
                                            "time", _sec,
                                            "isLocal", true,
                                            "easetype", iTween.EaseType.easeOutBack,
                                            "ignoretimescale", true
                                          ) );
            }
        }
    }
Пример #22
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    IEnumerator OnMissionComplete() {
        Game.PlayAsGod(true);
        Time.timeScale = 0.2f;
        yield return StartCoroutine ( CoroutineHelper.WaitForRealSeconds(2.0f) ); 

        // pause the game
        StartCoroutine(Game.Pause());

        // go to mission report state
        this.zombieFace.gameObject.SetActiveRecursively(false);
        this.txtDeadZombeCounter.gameObject.SetActiveRecursively(false);
        FinishScene.SetActiveRecursively(true);
        missionReportStartTime = Time.realtimeSinceStartup;
        timeMissionFinished = Time.time;
        State = UpdateMissionReport;
    }
Пример #23
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    void UpdateReloadDeactive () {
        PlayerGirl girl = Game.PlayerGirl() as PlayerGirl;
        ShootInfo shootInfo = girl.GetShootInfo();

        if ( shootInfo.NoBulletForReloading() == false &&
             shootInfo.isAmmoFull() == false )
        {
            EnableReloadButton ();
            ReloadButtonState = UpdateAcceptReload;
            return;
        }
    }
Пример #24
0
 public void AddState(int stateId, StateTransition onEnter, StateTransition onExit, StateUpdate onUpdate, StateUpdate onFixedUpdate)
 {
     if (!states.ContainsKey(stateId))
     {
         states.Add(stateId, new State()
         {
             OnEnter       = onEnter,
             OnExit        = onExit,
             OnUpdate      = onUpdate,
             OnFixedUpdate = onFixedUpdate
         });
     }
 }
Пример #25
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    void UpdateAcceptActiveReload () {
        PlayerGirl girl = Game.PlayerGirl() as PlayerGirl;

        //
        if ( girl.IsReloading() == false ) {
            StartCoroutine(HideActiveReloadBar("none"));
            DisableReloadButton();
            ReloadButtonState = UpdateReloadDeactive;
            return;
        }

        //
        if ( screenPad.ReloadButtonDown() ) {
            this.OnActiveReload();
            return;
        }

        //
        if ( screenPad.ReloadButtonPressing() ) {
            reloadButton.color.a = 1.0f;
            reloadButton.SetColor(reloadButton.color);
            reloadindEffect.color.a = 1.0f;
            reloadindEffect.SetColor(reloadindEffect.color);
        }
        else {
            reloadButton.color.a = 0.5f;
            reloadButton.SetColor(reloadButton.color);
            reloadindEffect.color.a = 0.5f;
            reloadindEffect.SetColor(reloadindEffect.color);
        }
    }
Пример #26
0
        /// <summary>
        ///     Executes the <paramref name="entry" />.
        /// </summary>
        /// <param name="entry">Transaction entry to be executed inside the <see cref="VirtualMachine" />.</param>
        /// <param name="stateUpdate"><see cref="Delta" /> to be used for execution environment construction</param>
        /// <param name="txTracer">Tracer to extract the execution steps for debugging or analytics.</param>
        /// <param name="readOnly">Defines whether the state should be reverted after the execution.</param>
        /// <exception cref="TransactionCollisionException">Thrown when deployment address already has some code.</exception>
        /// <exception cref="OutOfGasException">Thrown when not enough gas is available for deposit.</exception>
        private void Execute(PublicEntry entry, StateUpdate stateUpdate, ITxTracer txTracer, bool readOnly)
        {
            var spec = _specProvider.GetSpec(stateUpdate.Number);

            var(sender, recipient) = ExtractSenderAndRecipient(entry);
            var isPrecompile = recipient.IsPrecompiled(spec);
            var env          = PrepareEnv(entry, sender, recipient, stateUpdate, isPrecompile);

            var gasLimit     = entry.GasLimit;
            var intrinsicGas = CalculateIntrinsicGas(entry, spec);

            if (_logger.IsEnabled(LogEventLevel.Verbose))
            {
                _logger.Verbose("Executing entry {entry}", entry);
            }

            if (!ValidateSender(entry, env, txTracer))
            {
                return;
            }

            if (!ValidateIntrinsicGas(entry, env, intrinsicGas, txTracer))
            {
                return;
            }

            if (!ValidateDeltaGasLimit(entry, env, txTracer))
            {
                return;
            }

            if (!_stateProvider.AccountExists(env.Sender))
            {
                if (env.GasPrice == UInt256.Zero)
                {
                    _stateProvider.CreateAccount(env.Sender, UInt256.Zero);
                }
            }

            if (!ValidateSenderBalance(entry, env, intrinsicGas, txTracer))
            {
                return;
            }

            if (!ValidateNonce(entry, env, txTracer))
            {
                return;
            }

            InitEntryExecution(env, gasLimit, spec, txTracer);

            // we prepare two fields to track the amount of gas spent / left
            var unspentGas = gasLimit - intrinsicGas;
            var spentGas   = gasLimit;

            // the snapshots are needed to revert the subroutine state changes in case of an VM exception
            var stateSnapshot   = _stateProvider.TakeSnapshot();
            var storageSnapshot = _storageProvider.TakeSnapshot();

            // we subtract value from sender
            // it will be added to recipient at the later stage (inside the VM)
            _stateProvider.SubtractFromBalance(sender, env.Value, spec);

            // we fail unless we succeed
            var statusCode = StatusCode.Failure;
            TransactionSubstate substate = null;

            try
            {
                if (entry.IsValidDeploymentEntry)
                {
                    PrepareContractAccount(env.CodeSource);
                }

                var executionType = entry.IsValidDeploymentEntry ? ExecutionType.Create : ExecutionType.Call;
                using (var state = new VmState((long)unspentGas, env, executionType, isPrecompile, true, false))
                {
                    substate   = _virtualMachine.Run(state, txTracer);
                    unspentGas = (ulong)state.GasAvailable;
                }

                if (substate.ShouldRevert || substate.IsError)
                {
                    if (_logger.IsEnabled(LogEventLevel.Verbose))
                    {
                        _logger.Verbose("Restoring state from before transaction");
                    }

                    _stateProvider.Restore(stateSnapshot);
                    _storageProvider.Restore(storageSnapshot);
                }
                else
                {
                    if (entry.IsValidDeploymentEntry)
                    {
                        DeployCode(env, substate, ref unspentGas, spec);
                    }

                    DestroyAccounts(substate);
                    statusCode = StatusCode.Success;
                }

                spentGas = Refund(gasLimit, unspentGas, substate, env, spec);
            }
            catch (Exception ex) when(ex is EvmException || ex is OverflowException)
            {
                if (_logger.IsEnabled(LogEventLevel.Verbose))
                {
                    _logger.Verbose($"EVM EXCEPTION: {ex.GetType().Name}");
                }

                _stateProvider.Restore(stateSnapshot);
                _storageProvider.Restore(storageSnapshot);
            }

            if (_logger.IsEnabled(LogEventLevel.Verbose))
            {
                _logger.Verbose("Gas spent: " + spentGas);
            }

            var gasBeneficiary = stateUpdate.GasBeneficiary;
            var wasBeneficiaryAccountDestroyed = statusCode != StatusCode.Failure &&
                                                 (substate?.DestroyList.Contains(gasBeneficiary) ?? false);

            if (!wasBeneficiaryAccountDestroyed)
            {
                if (!_stateProvider.AccountExists(gasBeneficiary))
                {
                    _stateProvider.CreateAccount(gasBeneficiary, spentGas * env.GasPrice);
                }
                else
                {
                    _stateProvider.AddToBalance(gasBeneficiary, spentGas * env.GasPrice, spec);
                }
            }

            if (!readOnly)
            {
                _storageProvider.Commit(txTracer.IsTracingState ? txTracer : null);
                _stateProvider.Commit(spec, txTracer.IsTracingState ? txTracer : null);
                stateUpdate.GasUsed += (long)spentGas;
            }
            else
            {
                _storageProvider.Reset();
                _stateProvider.Reset();
            }

            if (txTracer.IsTracingReceipt)
            {
                if (statusCode == StatusCode.Failure)
                {
                    txTracer.MarkAsFailed(env.CodeSource, (long)spentGas,
                                          substate?.ShouldRevert ?? false ? substate.Output : Bytes.Empty, substate?.Error);
                }
                else
                {
                    if (substate == null)
                    {
                        throw new InvalidOperationException("Substate should not be null after a successful VM run.");
                    }

                    txTracer.MarkAsSuccess(env.CodeSource, (long)spentGas, substate.Output,
                                           substate.Logs.Any() ? substate.Logs.ToArray() : LogEntry.EmptyLogs);
                }
            }
        }
Пример #27
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    public void OnReload () {
        //
        this.StopActiveReload();
        PlayerGirl girl = Game.PlayerGirl() as PlayerGirl;
        // ShootInfo shootInfo = girl.GetShootInfo();
        this.ShowActiveReloadBar();

        {
            // first enable the reload status
            reloadButton.color.a = 1.0f;
            reloadButton.SetColor(reloadButton.color);
            reloadindEffect.color.a = 1.0f;
            reloadindEffect.SetColor(reloadindEffect.color);

            iTween.ScaleFrom ( this.reloadButton.gameObject, new Vector3( 1.5f, 1.5f, 1.5f ), 0.4f ); 
            iTween.RotateBy ( this.reloadindEffect.gameObject, 
                              iTween.Hash( "amount", Vector3.forward,
                                           "time", 1.0f,
                                           "easetype", iTween.EaseType.easeInOutQuad, 
                                           "looptype", iTween.LoopType.loop 
                                         ) ); 
        }

        {
            //
            float reloadTime = girl.ReloadTime();
            Vector3 newPos = this.activeReloadFloat.transform.position 
                + new Vector3( activeReloadBar.width, 0.0f, 0.0f );
            iTween.MoveTo ( this.activeReloadFloat.gameObject, 
                            iTween.Hash( "position", newPos,
                                         "time", reloadTime,
                                         "easetype", iTween.EaseType.easeOutQuart 
                                       ) ); 

            //
            girl.SendMessage("OnReload");
            this.hint_reloadBin.SetActiveRecursively(false);
            if ( this.hint_tapAgain.active == false ) {
                this.hint_tapAgain.SetActiveRecursively(true);
                this.hint_tapAgain.SendMessage("StartBlink");
            }
            this.ReloadButtonState = UpdateAcceptActiveReload;
        }
    }
Пример #28
0
        public void Test_BitTricks_Min_Signed()
        {
            Tools tools = this.CreateTools();

            tools.StateConfig.Set_All_Reg_Off();
            tools.StateConfig.RAX = true;
            tools.StateConfig.RBX = true;
            tools.StateConfig.RDX = true;

            return;                        // this trick does not seem to be correct?!

            string line1 = "sub rax, rbx"; // Will not work if overflow here!
            string line2 = "cqo";          // rdx1 = (rax0 > rbx0) ? -1 : 0
            string line3 = "and rdx, rax"; // rdx2 = (rax0 > rbx0) ? 0 : (rax0 - rbx0)
            string line4 = "add rbx, rdx"; // rbx1 = (rax0 > rbx0) ? (rbx0 + 0) : (rbx0 + rax0 - rbx0)

            {                              // forward
                State   state = this.CreateState(tools);
                Context ctx   = state.Ctx;

                if (true)
                {
                    ulong       rax_value   = 0x61a4292198602827;
                    ulong       rbx_value   = 0x8739140220c24080;
                    StateUpdate updateState = new StateUpdate("!PREVKEY", "!NEXTKEY", state.Tools);
                    updateState.Set(Rn.RAX, rax_value);
                    updateState.Set(Rn.RBX, rbx_value);
                    state.Update_Forward(updateState);
                    if (LogToDisplay)
                    {
                        Console.WriteLine("Initially, we know:\n" + state);
                    }
                }

                BitVecExpr rax0 = state.Create(Rn.RAX);
                BitVecExpr rbx0 = state.Create(Rn.RBX);

                {
                    state.Solver.Assert(state.Ctx.MkNot(ToolsFlags.Create_OF_Sub(rax0, rbx0, rax0.SortSize, ctx))); // this code only works when there is no overflow in line1
                }
                {                                                                                                   // line 1
                    state = Runner.SimpleStep_Forward(line1, state);
                    // retrieve the overflow after line 1, OF has to be zero for the code to work
                    state.Solver.AssertAndTrack(ctx.MkNot(state.Create(Flags.OF)), ctx.MkBoolConst("OF-ZERO"));
                    Assert.AreEqual(Status.SATISFIABLE, state.Solver.Check());
                    if (LogToDisplay)
                    {
                        Console.WriteLine("After \"" + line1 + "\", we know:\n" + state);
                    }
                }
                { // line 2
                    state = Runner.SimpleStep_Forward(line2, state);
                    // if (logToDisplay) Console.WriteLine("After \"" + line2 + "\", we know:\n" + state);
                    BoolExpr t2 = ctx.MkEq(state.Create(Rn.RDX), ctx.MkITE(ctx.MkBVSGT(rax0, rbx0), ctx.MkBV(0xFFFF_FFFF_FFFF_FFFF, 64), ctx.MkBV(0, 64)));
                    // Assert.AreEqual(Tv5.ONE, ToolsZ3.GetTv5(t2, state.Solver, state.Ctx));
                }
                {
                    state = Runner.SimpleStep_Forward(line3, state);
                    // if (logToDisplay) Console.WriteLine("After \"" + line3 + "\", we know:\n" + state);
                    // BoolExpr t2 = ctx.MkEq(state.Get(Rn.RDX), ctx.MkITE(ctx.MkBVSGT(rax0, rbx0), ctx.MkBV(0, 64), ctx.MkBVSub(rax0, rbx0)));
                    // Assert.AreEqual(Tv5.ONE, ToolsZ3.GetTv5(t2, state.Solver, state.Ctx));
                }
                {
                    state = Runner.SimpleStep_Forward(line4, state);
                    if (LogToDisplay)
                    {
                        Console.WriteLine("After \"" + line4 + "\", we know:\n" + state);
                    }
                }

                // ebx is minimum of ebx and eax
                BitVecExpr rbx1 = state.Create(Rn.RBX);
                BoolExpr   t    = ctx.MkEq(rbx1, ctx.MkITE(ctx.MkBVSGT(rax0, rbx0), rbx0, rax0));

                if (false)
                {
                    state.Solver.Push();
                    state.Solver.AssertAndTrack(t, ctx.MkBoolConst("MIN_RAX_RBX"));
                    Status s = state.Solver.Check();
                    if (LogToDisplay)
                    {
                        Console.WriteLine("Status A = " + s + "; expected " + Status.SATISFIABLE);
                    }

                    if (s == Status.UNSATISFIABLE)
                    {
                        if (LogToDisplay)
                        {
                            Console.WriteLine("UnsatCore has " + state.Solver.UnsatCore.Length + " elements");
                        }

                        foreach (BoolExpr b in state.Solver.UnsatCore)
                        {
                            if (LogToDisplay)
                            {
                                Console.WriteLine("UnsatCore=" + b);
                            }
                        }

                        if (LogToDisplay)
                        {
                            Console.WriteLine(state.Solver);
                        }

                        Assert.Fail();
                    }
                    state.Solver.Pop();
                }
                if (true)
                {
                    state.Solver.Push();
                    state.Solver.Assert(ctx.MkNot(t), ctx.MkBoolConst("NOT_MIN_RAX_RBX"));
                    Status s = state.Solver.Check();
                    if (LogToDisplay)
                    {
                        Console.WriteLine("Status B = " + s + "; expected " + Status.UNSATISFIABLE);
                    }

                    if (s == Status.SATISFIABLE)
                    {
                        if (LogToDisplay)
                        {
                            Console.WriteLine("Model=" + state.Solver.Model);
                        }

                        Assert.Fail();
                    }
                    state.Solver.Pop();
                }
                Assert.AreEqual(Tv.ONE, ToolsZ3.GetTv(t, state.Solver, state.Ctx));
            }
        }
Пример #29
0
    // ------------------------------------------------------------------ 
    // Desc: 
    // ------------------------------------------------------------------ 

    public void OnActiveReload () {
        PlayerGirl girl = Game.PlayerGirl() as PlayerGirl;

        float float_pos = this.activeReloadFloat.transform.position.x;
        float min_arpos = this.activeReloadZone.transform.position.x
            - this.activeReloadZone.width * 0.5f;
        float max_arpos = this.activeReloadZone.transform.position.x
            + this.activeReloadZone.width * 0.5f;

        if ( float_pos >= min_arpos && float_pos <= max_arpos ) {
            girl.SendMessage("OnActiveReload");
            StartCoroutine(HideActiveReloadBar("successful"));
            DisableReloadButton();
            this.ReloadButtonState = UpdateReloadDeactive;
        }
        else {
            StartCoroutine(HideActiveReloadBar("failed"));
            DisableReloadButton();
            this.ReloadButtonState = UpdateReloadDeactive;
        }
    }
Пример #30
0
 public void UpdateState(StateUpdate stateUpdate)
 {
     _tPClient.SendAsync(stateUpdate);
 }
Пример #31
0
        /*
         * also need to test:
         * BALANCE
         * EXTCODECOPY
         * CALLDATACOPY
         * GASPRICE
         * CREATE
         */

        private static GethLikeTxTracer RunVirtualMachine(byte[] code)
        {
            GethLikeTxTracer txTracer = new GethLikeTxTracer(GethTraceOptions.Default);

            IDb stateDbDevice = new MemDb();
            IDb codeDbDevice  = new MemDb();

            ISnapshotableDb stateDb = new StateDb(stateDbDevice);
            ISnapshotableDb codeDb  = new StateDb(codeDbDevice);

            IStateProvider   stateProvider   = new StateProvider(stateDb, codeDb, LimboLogs.Instance);
            IStorageProvider storageProvider = new StorageProvider(stateDb, stateProvider, LimboLogs.Instance);

            IStateUpdateHashProvider stateUpdateHashProvider = new StateUpdateHashProvider();
            ISpecProvider            specProvider            = new CatalystSpecProvider();

            // these values will be set by the tx processor within the state update logic
            ExecutionEnvironment env = new ExecutionEnvironment();

            env.Originator       = Address.Zero;         // tx sender
            env.Sender           = Address.Zero;         // sender of this call for a given call depth
            env.ExecutingAccount =
                Address.Zero;                            // account in which context the code is executed, it may be different from the code source when invoking a lib
            env.Value = 1
                        .Kat();                          // sometimes the value is just a description of an upper level call to be used by a an invoke library method
            env.TransferValue = 1.Kat();                 // this is the actual value transferred from sender to recipient
            env.GasPrice      = 0;                       // conversion from gas units to FULs
            env.InputData     =
                new byte[0];                             // only needed for contracts requiring input (ensure that this is not limited to 60bytes)
            env.CallDepth = 0;                           // zero when starting tx

            StateUpdate stateUpdate = new StateUpdate(); // Catalyst single state update context (all phases together)

            stateUpdate.Difficulty =
                1;                                     // some metric describing the state update that is relevant for consensus
            stateUpdate.Number         = 1;            // state update sequence number
            stateUpdate.Timestamp      = 1;            // state update T0
            stateUpdate.GasLimit       = 1_000_000;    // max gas units to be available for this tx inside the kvm
            stateUpdate.GasBeneficiary = Address.Zero; // will get all the gas fees
            stateUpdate.GasUsed        =
                0L;                                    // zero if this is the first transaction in the update (accumulator over txs)
            env.CurrentBlock = stateUpdate;

            // this would be loaded by the tx processor from the recipient's code storage
            CodeInfo codeInfo = new CodeInfo(code);

            env.CodeInfo   = codeInfo;
            env.CodeSource = Address.Zero;

            // this would be set by the tx processor that understands the type of transaction
            VmState vmState = new VmState(1_000_000L, env, ExecutionType.Transaction, false, true, false);

            KatVirtualMachine virtualMachine = new KatVirtualMachine(
                stateProvider,
                storageProvider,
                stateUpdateHashProvider,
                specProvider,
                new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256")),
                new FfiWrapper(),
                LimboLogs.Instance);

            virtualMachine.Run(vmState, txTracer);
            return(txTracer);
        }