/**
  * Eventhandler which is reasponsible for handling
  * realtime in game messages
  *
  * Parameter:
  * sender (object): the boxed object, which invoked this event
  * msg (IMatchState): A nakama objece, which contains information
  *                    about the state received like:
  *                    - State (byteArray): the unencoded match state as byte array
  *                    - UserPresence (IUserPresence): Information about the user,
  *                                                    who sent the state.
  */
 private void OnMatchState(object sender, IMatchState msg)
 {
     nvpEventManager.INSTANCE.InvokeEvent(
         GameEvents.OnRealtimeMessageReceived,
         msg.OpCode,
         msg);
 }
Ejemplo n.º 2
0
        public int CalculateMatchPrice(IMatchState state, int position, int displacement, int length)
        {
            var bitLength = 0;

            var matches = state.CountMatches(position) + 1;

            if (matches >= 16 && (matches - 16) % 0x7F == 0)
            {
                bitLength += 8;
            }

            var dispBitCount = GetBitCount(displacement);

            bitLength += dispBitCount / 7 * 8 + (dispBitCount % 7 <= 3 ? 4 : 12);

            if (length <= 0xF)
            {
                bitLength += 4;
            }
            else
            {
                var lengthBitCount = GetBitCount(length);
                bitLength += 4 + lengthBitCount / 7 * 8 + (lengthBitCount % 7 > 0 ? 8 : 0);
            }

            return(bitLength);
        }
Ejemplo n.º 3
0
        public MatchContext SetNextState(IMatchState nextState)
        {
            Console.WriteLine("-- STATE HAS CHANGED --");
            _matchState = nextState;

            return(this);
        }
Ejemplo n.º 4
0
 public TennisMatch(ITournamentRules tournamentRules, Func <TennisMatch, IMatchState> matchStateFactory)
     : base(new Party("A"), new Party("B"))
 {
     _tournamentRules = tournamentRules;
     _matchState      = matchStateFactory(this);
     _currentSet      = _matchState.GetNextSet(tournamentRules);
 }
Ejemplo n.º 5
0
    private void OnMatchState(object s, IMatchState state)
    {
        // code for evaluating game messages
        var    content = System.Text.Encoding.UTF8.GetString(state.State);
        object message = null;

        switch (state.OpCode)
        {
        case PositionUpdateMessage.OpCode:
            message = content.FromJson <PositionUpdateMessage>();
            break;

        case RocketFiredMessage.OpCode:
            message = content.FromJson <RocketFiredMessage>();
            break;

            //default:
            //    Debug.LogFormat("User {0} sent {1}", state.UserPresence.UserId, content);
            //    nvpEventManager.INSTANCE.InvokeEvent(GameEvents.OnMessageReceived, state.UserPresence.UserId, content);
            //    break;
        }

        if (message == null)
        {
            return;
        }
        nvpEventManager.INSTANCE.InvokeEvent(GameEvents.OnMessageReceived, state.UserPresence.UserId, message);
    }
Ejemplo n.º 6
0
 public int CalculateLiteralPrice(IMatchState state, int position, int value)
 {
     // One raw value is encoded with huffman; The huffman code length will be approximated at 6 bits after some heuristics were taken
     // Additionally the length is also huffman coded; We approximate 3 bit for one length index value and to also accomodate
     // for possible coming length indexes
     // Each length can also be followed by additional bits for intermediate lengths, we approximate them with 3 bits
     return(6 + 3 + 3);
 }
Ejemplo n.º 7
0
 public int CalculateMatchPrice(IMatchState state, int position, int displacement, int length)
 {
     // One match is encoded with two huffman values
     // The length value can be at max 6 bits, therefore we will approximate it at 3 bits;
     // The displacement value can be at max 5 bits, therefore we will approximate it at 2 bits;
     // For additional bits to reach intermediate values, we approximate 3 bits
     return(3 + 2 + 3);
 }
Ejemplo n.º 8
0
        public int CalculateMatchPrice(IMatchState state, int position, int displacement, int length)
        {
            if (length >= 0x12)
            {
                return(25);
            }

            return(17);
        }
        public int CalculateMatchPrice(IMatchState state, int position, int displacement, int length)
        {
            if (displacement == 0 && length >= 0x13)
            {
                // Longest RLE match
                return(25);
            }

            // Otherwise default match cost
            return(17);
        }
        /// <summary>
        /// Decodes match state message json from byte form of matchState.State and then sends it to ReceiveMatchStateHandle
        /// for further reading and handling
        /// </summary>
        /// <param name="matchState"></param>
        private void ReceiveMatchStateMessage(IMatchState matchState)
        {
            string messageJson = System.Text.Encoding.UTF8.GetString(matchState.State);

            if (string.IsNullOrEmpty(messageJson))
            {
                return;
            }

            ReceiveMatchStateHandle(matchState.OpCode, messageJson);
        }
Ejemplo n.º 11
0
        public int CalculateLiteralPrice(IMatchState state, int position, int value)
        {
            var literalCount = state.CountLiterals(position) % 3 + 1;

            if (literalCount == 3)
            {
                return(6);
            }

            return(10);
        }
Ejemplo n.º 12
0
        private void NakamaServerOnMatchStateReceived(IMatchState matchState)
        {
            var decodedState = Encoding.UTF8.GetString(matchState.State);
            var data         = JsonConvert.DeserializeObject <Dictionary <string, Vector2> >(decodedState).First();

            if (!data.Key.Equals(Id))
            {
                return;
            }
            UpdatePosition(data.Value);
        }
Ejemplo n.º 13
0
        public void ChangeMatchState(IMatchState matchState)
        {
            DIContainer.Logger.Debug(string.Format("Switching to {0}", matchState.GetType()));

            if (CurrentMatchState.Value != null)
            {
                CurrentMatchState.Value.OnDeactivate();
            }

            CurrentMatchState.SetValueAndForceNotify(matchState);
            CurrentMatchState.Value.OnActivate(this);
        }
Ejemplo n.º 14
0
        private void ReceiveMatchStateMessage(object sender, IMatchState e)
        {
            var diffTime = (float)(DateTime.Now - _timeOfLastState).TotalSeconds;

            PublicMatchState state = PublicMatchState.Parser.ParseFrom(e.State);
            var cl = state.Combatlog.ToArray();

            OnCombatLogUpdate?.Invoke(cl, diffTime);
            OnNewWorldUpdate?.Invoke(state, diffTime);

            _timeOfLastState = DateTime.Now;
        }
Ejemplo n.º 15
0
    private void OnReceive(IMatchState state)
    {
        if (state.OpCode == OP_CODE_TIME_REQUEST)
        {
            var base64 = Convert.FromBase64String(Encoding.UTF8.GetString(state.State));
            var handle = GCHandle.Alloc(base64, GCHandleType.Pinned);
            var buffer = (DataTimeState)Marshal.PtrToStructure(
                handle.AddrOfPinnedObject(),
                typeof(DataTimeState));
            handle.Free();
            SetTimeStamp(ref buffer);
            Send(buffer, OP_CODE_TIME_RESPONSE);
        }
        else if (state.OpCode == OP_CODE_TIME_RESPONSE)
        {
            var base64 = Convert.FromBase64String(Encoding.UTF8.GetString(state.State));
            var handle = GCHandle.Alloc(base64, GCHandleType.Pinned);
            var buffer = (DataTimeState)Marshal.PtrToStructure(
                handle.AddrOfPinnedObject(),
                typeof(DataTimeState));
            handle.Free();

            var local = IsLead
                                ? DateTime.FromBinary(buffer.TimeLead)
                                : DateTime.FromBinary(buffer.TimeFollow);
            var remote = IsLead
                                ? DateTime.FromBinary(buffer.TimeFollow)
                                : DateTime.FromBinary(buffer.TimeLead);

            _timeProbe[buffer.Sequence]              = buffer;
            _timeProbe[buffer.Sequence].Roundtrip    = (DateTime.UtcNow - local).Ticks;
            _timeProbe[buffer.Sequence].Compensation = (local - remote).Ticks;

            Interlocked.Increment(ref _timeProbesReceived);
        }
        else if (state.OpCode == OP_CODE_STATE)
        {
            var base64   = Convert.FromBase64String(Encoding.UTF8.GetString(state.State));
            var handle   = GCHandle.Alloc(base64, GCHandleType.Pinned);
            var receiver = (DataFrameState)Marshal.PtrToStructure(
                handle.AddrOfPinnedObject(),
                typeof(DataFrameState));
            handle.Free();
            // transform (was set at sim update)
            //var packetTime = DateTime.FromBinary(receiver.Time);
            //packetTime += IsLead ? TimeSpan.Zero : _approxClockLag;
            //receiver.Time = packetTime.ToBinary();
            Composition.FrameSwap(ref receiver);
            // push
            Composition.ControllerSim.PushRemote(receiver);
        }
    }
Ejemplo n.º 16
0
        public ChessMatchState(Game game)
        {
            //Managers
            m_inputManger      = (IInputManager)game.Services.GetService(typeof(IInputManager));
            m_gameStateManager = (IGameStateManager)game.Services.GetService(typeof(IGameStateManager));
            m_graphicsManager  = (IGraphicsManager)game.Services.GetService(typeof(IGraphicsManager));
            m_resourceManager  = (IResourceManager)game.Services.GetService(typeof(IResourceManager));
            m_audioManager     = (IAudioManager)game.Services.GetService(typeof(IAudioManager));

            //Chess match stuff
            m_matchState = WhitePiecePicking.GetMatchState(this);
            m_chessMatch = new ChessMatch(this);
        }
        public int CalculateMatchPrice(IMatchState state, int position, int displacement, int length)
        {
            if (length >= 2 && length <= 5 && displacement >= 1 && displacement <= 0x10)
            {
                return(8);
            }
            if (length >= 3 && length <= 0x12 && displacement >= 1 && displacement <= 0x400)
            {
                return(16);
            }

            return(24);
        }
Ejemplo n.º 18
0
        public int CalculateMatchPrice(IMatchState state, int position, int displacement, int length)
        {
            var bitCount = displacement <= 0x4000 ? 5 : 3;

            length -= 2;
            if (length > (1 << bitCount) - 1)
            {
                var vlePrice = CalculateVariableLength(length, bitCount);
                return(24 + vlePrice);
            }

            return(24);
        }
Ejemplo n.º 19
0
        public int CalculateMatchPrice(IMatchState state, int position, int displacement, int length)
        {
            if (displacement > 4 && length > 0x12)
            {
                throw new InvalidOperationException("Invalid match for Lze.");
            }

            if (displacement <= 4)
            {
                return(10);
            }

            return(18);
        }
Ejemplo n.º 20
0
        public int CalculateLiteralPrice(IMatchState state, int position, int value)
        {
            var literals = state.CountLiterals(position) + 1;

            if (literals % 0x1FFF == 1)
            {
                return(16);
            }
            if (literals % 0x1FFF == 0x20)
            {
                return(16);
            }

            return(8);
        }
        public int CalculateLiteralPrice(IMatchState state, int position, int value)
        {
            var literalCount = state.CountLiterals(position) % 0x100BE + 1;

            if (literalCount == 0xC0)
            {
                return(16);
            }
            if (literalCount == 0x40)
            {
                return(16);
            }

            return(8);
        }
Ejemplo n.º 22
0
        public int CalculateLiteralPrice(IMatchState state, int position, int value)
        {
            // 1 flag bit
            // n bit value (huffman approximation)
            switch (_huffmanMode)
            {
            case 1:
                return(4);

            case 2:
                return(7);

            default:
                return(9);
            }
        }
    /**
     * Is called by nvpNakamaManager-Script when it receives a realtime message.
     */
    void OnRealtimeMessageReceived(object sender, object msgObject)
    {
        IMatchState msg = msgObject as IMatchState;

        switch (msg.OpCode)
        {
        case (long)NakamaOpCodes.PositionMessage:
            var json = System.Text.Encoding.UTF8.GetString(msg.State);
            _networkPosition  = JsonParser.FromJson <SerializableVector3>(json).ToVector3();
            _networkPosition += (_networkPosition - _currentPosition);
            break;

        default:
            break;
        }
    }
Ejemplo n.º 24
0
        public void LoadContent()
        {
            //Load models
            m_chessboardModel  = m_resourceManager.GetModel(GameModelKey.Chessboard);
            m_lettersModel     = m_resourceManager.GetModel(GameModelKey.Letters);
            m_whitePawnModel   = m_resourceManager.GetModel(GameModelKey.WhitePawn);
            m_whiteRookModel   = m_resourceManager.GetModel(GameModelKey.WhiteRook);
            m_whiteKnightModel = m_resourceManager.GetModel(GameModelKey.WhiteKnight);
            m_whiteBishopModel = m_resourceManager.GetModel(GameModelKey.WhiteBishop);
            m_whiteQueenModel  = m_resourceManager.GetModel(GameModelKey.WhiteQueen);
            m_whiteKingModel   = m_resourceManager.GetModel(GameModelKey.WhiteKing);
            m_blackPawnModel   = m_resourceManager.GetModel(GameModelKey.BlackPawn);
            m_blackRookModel   = m_resourceManager.GetModel(GameModelKey.BlackRook);
            m_blackKnightModel = m_resourceManager.GetModel(GameModelKey.BlackKnight);
            m_blackBishopModel = m_resourceManager.GetModel(GameModelKey.BlackBishop);
            m_blackQueenModel  = m_resourceManager.GetModel(GameModelKey.BlackQueen);
            m_blackKingModel   = m_resourceManager.GetModel(GameModelKey.BlackKing);

            //Load effects
            m_phongBumpReflect        = m_resourceManager.GetEffect(this, GameEffectKey.PhongBumpReflect);
            m_chessboardPickingEffect = m_resourceManager.GetEffect(this, GameEffectKey.SimpleTexture);
            m_phong = m_resourceManager.GetEffect(this, GameEffectKey.Phong);

            //Load textures
            m_chessboardPickingTexture = m_resourceManager.GetTexture(this, GameTextureKey.ChessboardPicking);
            m_chessboardDiffuse        = m_resourceManager.GetTexture(this, GameTextureKey.ChessboardDiffuse);
            m_chessboardBump           = m_resourceManager.GetTexture(this, GameTextureKey.ChessboardBump);
            m_lettersTexture           = m_resourceManager.GetTexture(this, GameTextureKey.LettersDiffuse);
            m_whitePiecesTexture       = m_resourceManager.GetTexture(this, GameTextureKey.WhitePiecesDiffuse);
            m_blackPiecesTexture       = m_resourceManager.GetTexture(this, GameTextureKey.BlackPiecesDiffuse);
            m_selectedPiecesTexture    = m_resourceManager.GetTexture(this, GameTextureKey.SelectedPiecesDiffuse);
            m_piecesBumpMap            = m_resourceManager.GetTexture(this, GameTextureKey.PiecesBumpMap);

            //Load fonts
            m_messageFont = m_resourceManager.GetFont(GameFontKey.VerdanaBig);

            //Setup
            m_chessboardPickingEffect.Parameters["Texture"].SetValue(m_chessboardPickingTexture);

            //Setup the match
            m_chessMatch.SetupGame();
            m_matchState = WhitePiecePicking.GetMatchState(this);

            //Reset the camera
            m_graphicsManager.ResetCamera();
        }
Ejemplo n.º 25
0
        public void AddPoint(Party party)
        {
            if (_matchState.MatchOver)
            {
                throw new InvalidOperationException("Cannot add points to won matches.");
            }

            _currentSet.AddPoint(party);

            if (_currentSet.SetOver)
            {
                IncreaseScore(party);
                _matchState = _matchState.SetAdded(party);

                if (!_matchState.MatchOver)
                {
                    _currentSet = _matchState.GetNextSet(_tournamentRules);
                }
            }
        }
        /// <summary>
        /// Decodes match state message json from byte form of matchState.State and then sends it to ReceiveMatchStateHandle
        /// for further reading and handling
        /// </summary>
        /// <param name="matchState"></param>
        private void ReceiveMatchStateMessage(IMatchState matchState)
        {
            string messageJson = System.Text.Encoding.UTF8.GetString(matchState.State);

            if (string.IsNullOrEmpty(messageJson))
            {
                return;
            }

            if (UseUnityMainThreadDispatcher)
            {
                UnityMainThreadDispatcher.Instance().Enqueue(() =>
                {
                    ReceiveMatchStateHandle(matchState.OpCode, messageJson);
                });
            }
            else
            {
                ReceiveMatchStateHandle(matchState.OpCode, messageJson);
            }
        }
Ejemplo n.º 27
0
        public int CalculateMatchPrice(IMatchState state, int position, int displacement, int length)
        {
            if (displacement == 0)
            {
                // Rle
                return(16 + (length - 4 > 0xF ? 8 : 0));
            }

            // Lz
            var price = 16;

            var cappedLength = Math.Max(length - 7, 0);

            price += (cappedLength / 0x1F) * 8;
            if (cappedLength % 0x1F > 0)
            {
                price += 8;
            }

            return(price);
        }
Ejemplo n.º 28
0
        public int CalculateLiteralPrice(IMatchState state, int position, int value)
        {
            var literals = state.CountLiterals(position) + 1;

            if (!state.HasMatches(position))
            {
                // Special first raw data read
                if (literals == 1)
                {
                    return(16);
                }
                if (literals == 0xef)
                {
                    return(16);
                }
                if (literals > 0xef && (literals - 3 - 0xF) % 0xFF == 1)
                {
                    return(16);
                }

                return(8);
            }

            if (literals == 4)
            {
                return(16);
            }
            if (literals == 0x13)
            {
                return(16);
            }
            if (literals > 0x13 && (literals - 3 - 0xF) % 0xFF == 1)
            {
                return(16);
            }

            return(8);
        }
Ejemplo n.º 29
0
    private void _socket_ReceivedMatchState(IMatchState obj)
    {
        var state = JsonUtility.FromJson <NakamaCommand>(System.Text.Encoding.UTF8.GetString(obj.State));

        switch (state.command)
        {
        case "start_game":
            _queue.Enqueue(new SendMessageObject()
            {
                messajeName  = "StartMatchWithoutNakama",
                messageParam = "Local"
            });
            //ui.SendMessage("startGame", obj.UserPresence.SessionId);
            break;

        case "move_character":
            state.sessionId = obj.UserPresence.SessionId;
            _queue.Enqueue(new SendMessageObject()
            {
                messajeName  = "updateCharacterPosition",
                messageParam = state
            });
            //ui.SendMessage("updateCharacterPosition", state);
            break;

        case "update_state":
            // un personauje a caido
            // state.sessionId = obj.UserPresence.SessionId;
            _queue.Enqueue(new SendMessageObject()
            {
                messajeName  = "updateCharacterState",
                messageParam = state
            });
            break;
        }
    }
Ejemplo n.º 30
0
        public int CalculateMatchPrice(IMatchState state, int position, int displacement, int length)
        {
            switch (_compressionMode)
            {
            case 1:
                // 1 flag bit
                // 2 displacement index bits
                // 3 bit displacement approximation
                // 4 bits match length
                return(10);

            case 2:
                if (length > 18)
                {
                    // variable length encoded match length
                    // an LZ match always encodes at least 4 bits outside the vle value
                    var vleLength = (length - 3) >> 4;

                    var result = 4;
                    while (vleLength > 0)
                    {
                        // 4 bits per vle part
                        result += 4;
                        // 3 bits are actual value part
                        vleLength >>= 3;
                    }

                    // 1 flag bit
                    // 3 set flag bits to mark vle match length
                    // n bits vle match length
                    // 1 flag bit
                    // 3 displacement index bits
                    // approximate displacement with 3 bits
                    return(1 + 3 + result + 1 + 3 + 3);
                }
                else
                {
                    // 1 flag bit
                    // 3 displacement index bits
                    // 4 match length bits
                    // approximate displacement with 3 bits
                    return(1 + 3 + 4 + 3);
                }

            case 3:
                if (length > 18)
                {
                    // variable length encoded match length
                    // an LZ match always encodes at least 3 bits outside the vle value
                    var vleLength = (length / 2 - 2) >> 3;

                    var result = 3;
                    while (vleLength > 0)
                    {
                        // 3 bits per vle part
                        result += 3;
                        // 2 bits are actual value part
                        vleLength >>= 2;
                    }

                    // 1 flag bit
                    // 2 set flag bits to mark vle match length
                    // n bits vle match length
                    // 1 flag bit
                    // 2 displacement index bits
                    // approximate displacement with 3 bits
                    return(1 + 2 + result + 1 + 2 + 3);
                }
                else
                {
                    // 1 flag bit
                    // 2 displacement index bits
                    // 3 match length bits
                    // approximate displacement with 3 bits
                    return(1 + 2 + 3 + 3);
                }

            case 5:
                if (displacement == 0)
                {
                    // 2 flag bits
                    // 6 bits match length
                    // 8 bit static value
                    return(2 + 6 + 8);
                }
                else
                {
                    // 2 displacement index bits
                    // approximate displacement with 3 bits
                    // 6 bits match length
                    return(2 + 3 + 6);
                }

            default:
                throw new InvalidOperationException("Compression mode not supported for price calculation.");
            }
        }
Ejemplo n.º 31
0
        public void AddPoint(Party party)
        {
            if (_matchState.MatchOver)
                throw new InvalidOperationException("Cannot add points to won matches.");

            _currentSet.AddPoint(party);

            if (_currentSet.SetOver)
            {
                IncreaseScore(party);
                _matchState = _matchState.SetAdded(party);

                if (!_matchState.MatchOver)
                    _currentSet = _matchState.GetNextSet(_tournamentRules);
            }
        }
Ejemplo n.º 32
0
 public TennisMatch(ITournamentRules tournamentRules, Func<TennisMatch, IMatchState> matchStateFactory)
     : base(new Party("A"), new Party("B"))
 {
     _tournamentRules = tournamentRules;
     _matchState = matchStateFactory(this);
     _currentSet = _matchState.GetNextSet(tournamentRules);
 }