Example #1
0
        /*	public override void AddEntity(Entity entity)
         *      {
         *          if (Entities == null) return;
         *
         *  lock (Entities)
         *              {
         *                      EntityManager.AddEntity(entity);
         *
         *                      if (Entities.TryAdd(entity.EntityId, entity))
         *                      {
         *                              if (entity.HealthManager is HealthManager)
         *                              {
         *
         *                              }
         *                              LevelEntityAddedEvent addedEvent = new LevelEntityAddedEvent(this, entity);
         *                              EventDispatcher.DispatchEvent(addedEvent);
         *
         *                              entity.SpawnToPlayers(GetAllPlayers());
         *                      }
         *                      else
         *                      {
         *                              throw new Exception("Entity existed in the players list when it should not");
         *                      }
         *              }
         *      }
         *
         *      public override void RemoveEntity(Entity entity)
         *      {
         *  if (Entities == null) return;
         *
         *              lock (Entities)
         *              {
         *                      if (!Entities.TryRemove(entity.EntityId, out entity)) return; // It's ok. Holograms destroy this play..
         *
         *                      LevelEntityRemovedEvent removedEvent = new LevelEntityRemovedEvent(this, entity);
         *                      EventDispatcher.DispatchEvent(removedEvent);
         *
         *                      entity.DespawnFromPlayers(GetAllPlayers());
         *              }
         *      }*/

        public override void AddPlayer(MiNET.Player newPlayer, bool spawn)
        {
            if (newPlayer.Skin == null)
            {
                newPlayer.Skin = new Skin()
                {
                    Animations = new List <Animation>(),
                    Cape       = new Cape()
                    {
                        Data = new byte[0]
                    },
                    Data          = ArrayOf <byte> .Create(8192, 0xFF),
                    Height        = 64,
                    Width         = 32,
                    IsPremiumSkin = false,
                    IsPersonaSkin = false,
                    Slim          = false
                };
            }

            base.AddPlayer(newPlayer, spawn);
            if (Players.TryGetValue(newPlayer.EntityId, out MiNET.Player p))
            {
                LevelEntityAddedEvent addedEvent = new LevelEntityAddedEvent(this, p);
                EventDispatcher.DispatchEventAsync(addedEvent);
            }
        }
Example #2
0
        /// <inheritdoc />
        public override void HandleMcpeBlockEntityData(McpeBlockEntityData message)
        {
            var playerPosition = KnownPosition.ToBlockCoordinates();

            if (playerPosition.DistanceTo(message.coordinates) > 1000)
            {
                return;
            }

            var nbt = message.namedtag.NbtFile.RootTag;

            if (nbt is NbtCompound compound)
            {
                var blockEntity = Level.GetBlockEntity(message.coordinates);
                EventDispatcher.DispatchEventAsync(new PlayerSetBlockEntityDataEvent(this, blockEntity, compound)).Then(
                    (result) =>
                {
                    if (result.IsCancelled)
                    {
                        return;
                    }

                    blockEntity.SetCompound(compound);
                    Level.SetBlockEntity(blockEntity);
                });
            }

            //base.HandleMcpeBlockEntityData(message);
        }
Example #3
0
        protected override async void OnPlayerJoin(PlayerEventArgs e)
        {
            if (_hasJoinedServer)
            {
                return;                       //Make sure this is only called once when we join the server for the first time.
            }
            _hasJoinedServer = true;

            await EventDispatcher.DispatchEventAsync(new PlayerJoinEvent(this));
        }
Example #4
0
        /// <summary>
        ///		Teleports the player to specified position
        /// </summary>
        /// <param name="newPosition">The position to teleport the player to</param>
        public override void Teleport(PlayerLocation newPosition)
        {
            EventDispatcher.DispatchEventAsync(new PlayerMoveEvent(this, KnownPosition, newPosition, true))
            .Then(
                result =>
            {
                if (result.IsCancelled)
                {
                    return;
                }

                base.Teleport(result.To);
            });
        }
Example #5
0
        /// <inheritdoc />
        public override void HandleMcpeSetPlayerGameType(McpeSetPlayerGameType message)
        {
            EventDispatcher.DispatchEventAsync(
                new PlayerGamemodeChangeEvent(
                    this, GameMode, (GameMode)message.gamemode,
                    PlayerGamemodeChangeEvent.PlayerGamemodeChangeTrigger.Self)).Then(
                response =>
            {
                if (response.IsCancelled)
                {
                    SetGamemode(response.OldGameMode);
                    return;
                }

                SetGamemode(response.NewGameMode);
            });
        }
Example #6
0
        /// <summary>
        ///		Handles incoming chat messages
        /// </summary>
        /// <param name="message"></param>
        public override void HandleMcpeText(McpeText message)
        {
            string text = message.message;

            if (string.IsNullOrEmpty(text))
            {
                return;
            }
            PlayerChatEvent chatEvent = new PlayerChatEvent(this, text);

            EventDispatcher.DispatchEventAsync(chatEvent).Then(result =>
            {
                if (result.IsCancelled)
                {
                    return;
                }

                Level.BroadcastMessage(chatEvent.Message, sender: this);
            });
        }
Example #7
0
        public override void RemovePlayer(MiNET.Player player, bool despawn = true)
        {
            if (player == null || player.EntityId == null)
            {
                return;
            }
            if (Players == null)
            {
                Log.Warn("OpenLevel.Players is null!");
                return;
            }

            if (Players.ContainsKey(player.EntityId))
            {
                base.RemovePlayer(player, despawn);
                if (!Players.ContainsKey(player.EntityId))
                {
                    LevelEntityRemovedEvent removedEvent = new LevelEntityRemovedEvent(this, player);
                    EventDispatcher.DispatchEventAsync(removedEvent);
                }
            }
        }
Example #8
0
        /// <summary>
        ///		Initializes the player
        /// </summary>
        public override void InitializePlayer()
        {
            PlayerLoginCompleteEvent e = new PlayerLoginCompleteEvent(this, DateTime.UtcNow);

            EventDispatcher.DispatchEventAsync(e).Then(result =>
            {
                if (result.IsCancelled)
                {
                    Disconnect("Error #357. Please report this error.");
                }
                else
                {
                    base.InitializePlayer();

                    Culture = CultureInfo.CreateSpecificCulture(PlayerInfo.LanguageCode.Replace('_', '-'));

                    HungerManager = new OpenHungerManager(this);
                    HealthManager = new OpenHealthManager(this);
                }
            });
            // HealthManager.PlayerTakeHit += HealthManagerOnPlayerTakeHit;
        }
Example #9
0
        protected override async void OnTicked(PlayerEventArgs e)
        {
            if (Monitor.TryEnter(_breakSync))
            {
                try
                {
                    if (IsBreakingBlock)
                    {
                        var elapsedTicks = BlockBreakTimer.Elapsed.TotalMilliseconds / 50;
                        if (elapsedTicks - BlockBreakTime >= 3)                         //3 ticks late?
                        {
                            StopBreak(BreakingBlockCoordinates);
                        }
                    }
                }
                finally
                {
                    Monitor.Exit(_breakSync);
                }
            }

            var isSpawned = IsSpawned;

            if (isSpawned && !_previousIsSpawned)
            {
                PlayerSpawnedEvent ev = new PlayerSpawnedEvent(this);
                await EventDispatcher.DispatchEventAsync(ev);
            }
            else if (!isSpawned && _previousIsSpawned)
            {
                PlayerDespawnedEvent ev = new PlayerDespawnedEvent(this);
                await EventDispatcher.DispatchEventAsync(ev);
            }

            _previousIsSpawned = isSpawned;

            _disguise?.Tick();
        }
Example #10
0
        protected override void HandleItemUseOnEntityTransaction(ItemUseOnEntityTransaction transaction)
        {
            if (!Level.TryGetEntity <Entity>(transaction.EntityId, out var entity) || !entity.IsSpawned || entity.HealthManager.IsDead || entity.HealthManager.IsInvulnerable)
            {
                return;
            }
            //     var entity = Level.GetEntity(transaction.EntityId);
            //  if (entity == null || !entity.IsSpawned || entity.HealthManager.IsDead || entity.HealthManager.IsInvulnerable)
            //      return;

            var actionType = (McpeInventoryTransaction.ItemUseOnEntityAction)transaction.ActionType;

            EntityInteractEvent interactEvent = new EntityInteractEvent(entity, this, actionType);

            EventDispatcher.DispatchEventAsync(interactEvent).Then(result =>
            {
                if (result.IsCancelled)
                {
                    return;
                }

                base.HandleItemUseOnEntityTransaction(transaction);
            });
        }
Example #11
0
        /// <summary>
        ///		Handles player actions like Start & Stop break
        /// </summary>
        /// <param name="message"></param>
        public override void HandleMcpePlayerAction(McpePlayerAction message)
        {
            var action = (PlayerAction)message.actionId;

            lock (_breakSync)
            {
                if (GameMode == GameMode.Creative)
                {
                    return;
                }

                Block block;
                if (action == PlayerAction.StartBreak)
                {
                    block = Level.GetBlock(message.coordinates);
                    var inHand = Inventory.GetItemInHand();
                    var drops  = block.GetDrops(inHand);

                    float tooltypeFactor = drops == null || drops.Length == 0 ? 5f : 1.5f;                     // 1.5 if proper tool

                    var multiplier = 1f;
                    switch (inHand.ItemMaterial)
                    {
                    case ItemMaterial.None:
                        break;

                    case ItemMaterial.Wood:
                        multiplier = 2f;
                        break;

                    case ItemMaterial.Stone:
                        multiplier = 4f;
                        break;

                    case ItemMaterial.Gold:
                        multiplier = 12f;
                        break;

                    case ItemMaterial.Iron:
                        multiplier = 6f;
                        break;

                    case ItemMaterial.Diamond:
                        multiplier = 8f;
                        break;
                    }

                    foreach (var enchantment in inHand.GetEnchantings())
                    {
                        if (enchantment.Id == EnchantingType.Efficiency && enchantment.Level > 0)
                        {
                            multiplier += MathF.Sqrt(enchantment.Level) + 1;
                        }
                    }

                    if (Effects.TryGetValue(EffectType.Haste, out var effect))
                    {
                        if (effect is Haste haste && haste.Level > 0f)
                        {
                            multiplier *= 1f + (haste.Level * 0.2f);
                        }
                    }

                    var hardness = block.Hardness;

                    double breakTime = MathF.Ceiling((hardness * tooltypeFactor * 20f));

                    McpeLevelEvent message1 = McpeLevelEvent.CreateObject();
                    message1.eventId  = 3600;
                    message1.position = message.coordinates;
                    message1.data     = (int)((double)ushort.MaxValue / (breakTime / multiplier));

                    Level.RelayBroadcast(message1);

                    BlockFace face = (BlockFace)message.face;

                    IsBreakingBlock = true;
                    BlockBreakTimer.Restart();
                    BreakingBlockCoordinates = block.Coordinates;
                    BlockBreakTime           = breakTime / multiplier;
                    BreakingFace             = face;

                    //		Log.Info(
                    //			$"Start Breaking block. Hardness: {hardness} | ToolTypeFactor; {tooltypeFactor} | BreakTime: {breakTime} | Multiplier: {multiplier} | BLockBreakTime: {breakTime / multiplier} | IsBreaking: {IsBreakingBlock}");

                    var blockStartBreak = new BlockStartBreakEvent(this, block);
                    EventDispatcher.DispatchEventAsync(blockStartBreak).Then(result =>
                    {
                        if (result.IsCancelled)
                        {
                            SendBlockBreakEnd(block.Coordinates);
                            return;
                        }
                    });

                    return;
                }
                else if (action == PlayerAction.AbortBreak)
                {
                    var elapsed      = BlockBreakTimer.ElapsedMilliseconds;
                    var elapsedTicks = elapsed / 50d;

                    //	Log.Info($"!! Abort Break !!! Ticks elapsed: {elapsedTicks} | Required: {BlockBreakTime} | IsBreaking: {IsBreakingBlock}");

                    block = Level.GetBlock(message.coordinates);
                    if (IsBreakingBlock && BreakingBlockCoordinates == block.Coordinates)
                    {
                        IsBreakingBlock = false;
                        BlockBreakTimer.Reset();

                        EventDispatcher.DispatchEventAsync(new BlockAbortBreakEvent(this, block)).Then(result =>
                        {
                            if (!result.IsCancelled)
                            {
                                SendBlockBreakEnd(block.Coordinates);
                                return;
                            }
                        });
                    }

                    return;
                }
                else if (action == PlayerAction.StopBreak)
                {
                    var elapsed      = BlockBreakTimer.ElapsedMilliseconds;
                    var elapsedTicks = elapsed / 50d;

                    //Log.Info($"## !! Stop Break !!! Ticks elapsed: {elapsedTicks} | Required: {BlockBreakTime} | IsBreaking: {IsBreakingBlock}");

                    if (IsBreakingBlock)
                    {
                        //BlockFace face = (BlockFace) message.face;
                        if (elapsedTicks >= BlockBreakTime || Math.Abs(elapsedTicks - BlockBreakTime) < 2.5
                            )                     //Give a max time difference of 2.5 ticks.
                        {
                            StopBreak(BreakingBlockCoordinates);
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                        IsBreakingBlock = false;
                        BlockBreakTimer.Reset();
                    }

                    return;
                }
            }

            base.HandleMcpePlayerAction(message);
        }
Example #12
0
        protected override void HandleItemUseTransaction(ItemUseTransaction transaction)
        {
            var itemInHand = Inventory.GetItemInHand();

            switch ((McpeInventoryTransaction.ItemUseAction)transaction.ActionType)
            {
            case McpeInventoryTransaction.ItemUseAction.Destroy:
            {
                var target = Level.GetBlock(transaction.Position);

                PlayerInteractEvent interactEvent = new PlayerInteractEvent(this, itemInHand, transaction.Position,
                                                                            (BlockFace)transaction.Face,
                                                                            (target is Air)
                                                    ? PlayerInteractEvent.PlayerInteractType.LeftClickAir
                                                    : PlayerInteractEvent.PlayerInteractType.LeftClickBlock);

                EventDispatcher.DispatchEventAsync(interactEvent).Then(result =>
                    {
                        if (result.IsCancelled)
                        {
                            return;
                        }

                        base.HandleItemUseTransaction(transaction);
                    });

                return;
            }

            case McpeInventoryTransaction.ItemUseAction.Use:
            {
                if (!UseItem(itemInHand))
                {
                    //HandleNormalTransaction(transaction);
                    HandleTransactionRecords(transaction.TransactionRecords);
                    return;
                }

                break;
            }

            case McpeInventoryTransaction.ItemUseAction.Place:
            {
                var target = Level.GetBlock(transaction.Position);

                PlayerInteractEvent interactEvent = new PlayerInteractEvent(this, itemInHand, transaction.Position,
                                                                            (BlockFace)transaction.Face, (target is Air)
                                                    ? PlayerInteractEvent.PlayerInteractType.RightClickAir
                                                    : PlayerInteractEvent.PlayerInteractType.RightClickBlock);

                EventDispatcher.DispatchEventAsync(interactEvent).Then(result =>
                    {
                        if (result.IsCancelled)
                        {
                            return;
                        }

                        base.HandleItemUseTransaction(transaction);
                    });

                return;
            }
            }
        }
Example #13
0
 protected override async void OnPlayerLeave(PlayerEventArgs e)
 {
     await EventDispatcher.DispatchEventAsync(new PlayerQuitEvent(this));
 }