Exemplo n.º 1
0
		private bool IsOnGround(PlayerLocation position)
		{
			PlayerLocation pos = (PlayerLocation) position.Clone();
			pos.Y -= 0.1f;
			Block block = Level.GetBlock(new BlockCoordinates(pos));

			return block.Id != 0; // Should probably test for solid
		}
Exemplo n.º 2
0
        public Entity(int entityTypeId, Level level)
        {
            Height = 1;
            Width = 1;
            Length = 1;
            Gravity = 0.08;
            Drag = 0.02;

            EntityId = EntityManager.EntityIdUndefined;
            Level = level;
            EntityTypeId = entityTypeId;
            KnownPosition = new PlayerLocation();
            HealthManager = new HealthManager(this);
        }
Exemplo n.º 3
0
        public BedrockClient(Alex alex, IPEndPoint endpoint, PlayerProfile playerProfile, DedicatedThreadPool threadPool, BedrockWorldProvider wp) : base(endpoint,
                                                                                                                                                          playerProfile.Username, threadPool)
        {
            PlayerProfile           = playerProfile;
            CancellationTokenSource = new CancellationTokenSource();

            Alex          = alex;
            WorldProvider = wp;
            ConnectionAcceptedWaitHandle = new ManualResetEventSlim(false);
            MessageDispatcher            = new McpeClientMessageDispatcher(new BedrockClientPacketHandler(this, alex, CancellationTokenSource.Token));
            CurrentLocation = new MiNET.Utils.PlayerLocation(0, 0, 0);
            OptionsProvider = alex.Services.GetService <IOptionsProvider>();
            XblmsaService   = alex.Services.GetService <XBLMSAService>();

            base.ChunkRadius = Options.VideoOptions.RenderDistance;

            Options.VideoOptions.RenderDistance.Bind(RenderDistanceChanged);

            _threadPool = threadPool;
        }
Exemplo n.º 4
0
        public Player(MiNetServer server, IPEndPoint endPoint, Level level, PluginManager pluginManager, int mtuSize)
            : base(-1, level)
        {
            Rtt = -1;
            Width = 0.6;
            Length = 0.6;
            Height = 1.80;

            Popups = new List<Popup>();

            Server = server;
            EndPoint = endPoint;
            _mtuSize = mtuSize;
            Level = level;
            _pluginManager = pluginManager;

            Permissions = new PermissionManager(UserGroup.User);
            Permissions.AddPermission("*"); //All users can use all commands. (For debugging purposes)

            Inventory = new PlayerInventory(this);

            _chunksUsed = new Dictionary<Tuple<int, int>, ChunkColumn>();

            IsSpawned = false;
            IsConnected = true;

            KnownPosition = new PlayerLocation
            {
                X = Level.SpawnPoint.X,
                Y = Level.SpawnPoint.Y,
                Z = Level.SpawnPoint.Z,
                Yaw = 91,
                Pitch = 28,
                HeadYaw = 91
            };

            _sendTicker = new Timer(SendQueue, null, 10, 10); // RakNet send tick-time
        }
Exemplo n.º 5
0
        private bool IsInLava(PlayerLocation playerPosition)
        {
            var block = Entity.Level.GetBlock(playerPosition);

            if (block == null || (block.Id != 10 && block.Id != 11)) return false;

            return playerPosition.Y < Math.Floor(playerPosition.Y) + 1 - ((1/9) - 0.1111111);
        }
Exemplo n.º 6
0
        private void GenerateParticles(Random random, Level level, PlayerLocation point, float yoffset, Vector3 multiplier, double d)
        {
            float vx = (float) random.NextDouble();
            vx *= random.Next(2) == 0 ? 1 : -1;
            vx *= (float) multiplier.X;

            float vy = (float) random.NextDouble();
            //vy *= random.Next(2) == 0 ? 1 : -1;
            vy *= (float) multiplier.Y;

            float vz = (float) random.NextDouble();
            vz *= random.Next(2) == 0 ? 1 : -1;
            vz *= (float) multiplier.Z;

            McpeLevelEvent mobParticles = McpeLevelEvent.CreateObject();
            mobParticles.eventId = (short) (0x4000 | GetParticle(random.Next(0, m < 1 ? 2 : 5)));
            mobParticles.x = point.X + vx;
            mobParticles.y = (point.Y - 2) + yoffset + vy;
            mobParticles.z = point.Z + vz;
            level.RelayBroadcast(mobParticles);
        }
Exemplo n.º 7
0
 public Hologram(Level level, string text, Vector3 position) : base(64, level)
 {
     NameTag = text;
     KnownPosition = new PlayerLocation(position);
 }
Exemplo n.º 8
0
		public virtual void SpawnLevel(Level toLevel, PlayerLocation spawnPoint)
		{
			bool oldNoAi = NoAi;
			SetNoAi(true);

			// send teleport straight up, no chunk loading
			SetPosition(new PlayerLocation
			{
				X = KnownPosition.X, Y = 4000, Z = KnownPosition.Z, Yaw = 91, Pitch = 28, HeadYaw = 91,
			});

			//if (Level != null)
			{
				Level.RemovePlayer(this, true);
				Level.EntityManager.RemoveEntity(null, this);
			}

			Level = toLevel; // Change level
			SpawnPosition = spawnPoint;
			//Level.AddPlayer(this, "", false);
			// reset all health states
			HealthManager.ResetHealth();
			SendSetHealth();

			SendSetSpawnPosition();

			SendAdventureSettings();

			SendPlayerInventory();

			CleanCache();

			ForcedSendChunk(spawnPoint);

			// send teleport to spawn
			SetPosition(spawnPoint);

			SetNoAi(oldNoAi);

			Level.AddPlayer(this, true);

			Log.InfoFormat("Respawn player {0} on level {1}", Username, Level.LevelId);

			SendSetTime();

			ThreadPool.QueueUserWorkItem(delegate(object state) { ForcedSendChunks(); });
		}
Exemplo n.º 9
0
		private void ForcedSendChunk(PlayerLocation position)
		{
			lock (_sendChunkSync)
			{
				var chunkPosition = new ChunkCoordinates(position);

				McpeBatch chunk = Level.GenerateChunk(chunkPosition);
				var key = new Tuple<int, int>(chunkPosition.X, chunkPosition.Z);
				if (!_chunksUsed.ContainsKey(key))
				{
					_chunksUsed.Add(key, chunk);
				}

				if (chunk != null)
				{
					SendPackage(chunk, true);
				}
			}
		}
Exemplo n.º 10
0
        public virtual void SpawnLevel(Level toLevel, PlayerLocation spawnPoint)
        {
            SetNoAi(true);

            // send teleport straight up, no chunk loading
            SetPosition(new PlayerLocation
            {
                X = KnownPosition.X,
                Y = 4000,
                Z = KnownPosition.Z,
                Yaw = 91,
                Pitch = 28,
                HeadYaw = 91,
            });

            Level.RemovePlayer(this, true);
            Level.EntityManager.RemoveEntity(null, this);

            Level = toLevel; // Change level
            SpawnPosition = spawnPoint;
            Level.AddPlayer(this, "", false);
            // reset all health states
            HealthManager.ResetHealth();
            SendSetHealth();

            SendSetSpawnPosition();

            SendAdventureSettings();

            SendPlayerInventory();

            lock (_chunksUsed)
            {
                _chunksUsed.Clear();
            }

            ForcedSendChunksForKnownPosition(spawnPoint);

            // send teleport to spawn
            SetPosition(spawnPoint);

            SetNoAi(false);

            Level.SpawnToAll(this);
            IsSpawned = true;

            Log.InfoFormat("Respawn player {0} on level {1}", Username, Level.LevelId);

            SendSetTime();
        }
Exemplo n.º 11
0
        private void ForcedSendChunksForKnownPosition(PlayerLocation position)
        {
            var chunkPosition = new ChunkCoordinates(position);
            _currentChunkPosition = chunkPosition;

            foreach (McpeBatch chunk in Level.GenerateChunks(_currentChunkPosition, _chunksUsed))
            {
                SendPackage(chunk, true);
            }
        }
Exemplo n.º 12
0
        protected virtual void HandleRespawn(McpeRespawn msg)
        {
            ServerInfo serverInfo = Server.ServerInfo;
            try
            {
                Interlocked.Increment(ref serverInfo.ConnectionsInConnectPhase);

                // reset all health states
                HealthManager.ResetHealth();

                // send teleport to spawn
                KnownPosition = new PlayerLocation
                {
                    X = SpawnPosition.X,
                    Y = SpawnPosition.Y,
                    Z = SpawnPosition.Z,
                    Yaw = 91,
                    Pitch = 28,
                    HeadYaw = 91,
                };

                SendSetHealth();

                SendAdventureSettings();

                SendPlayerInventory();

                BroadcastSetEntityData();

                ThreadPool.QueueUserWorkItem(delegate(object state)
                {
                    Level.SpawnToAll(this);
                    SendChunksForKnownPosition();
                });

                IsSpawned = true;

                SendMovePlayer();

                Log.InfoFormat("Respawn player {0} on level {1}", Username, Level.LevelId);
            }
            finally
            {
                Interlocked.Decrement(ref serverInfo.ConnectionsInConnectPhase);
            }
        }
Exemplo n.º 13
0
        protected virtual void HandleMovePlayer(McpeMovePlayer message)
        {
            if (!IsSpawned || HealthManager.IsDead) return;

            lock (_moveSyncLock)
            {
                if (_lastPlayerMoveSequenceNUmber > message.DatagramSequenceNumber)
                {
                    Log.DebugFormat("Skipping move datagram {1}/{2} for player {0}", Username, _lastPlayerMoveSequenceNUmber, message.DatagramSequenceNumber);
                    return;
                }
                else
                {
                    _lastPlayerMoveSequenceNUmber = message.DatagramSequenceNumber;
                }

                if (_lastOrderingIndex > message.OrderingIndex)
                {
                    Log.DebugFormat("Skipping move ordering {1}/{2} for player {0}", Username, _lastOrderingIndex, message.OrderingIndex);
                    return;
                }
                else
                {
                    _lastOrderingIndex = message.OrderingIndex;
                }

                long td = DateTime.UtcNow.Ticks - LastUpdatedTime.Ticks;
                Vector3 origin = new Vector3(KnownPosition.X, 0, KnownPosition.Z);
                double distanceTo = origin.DistanceTo(new Vector3(message.x, 0, message.z));
                if (distanceTo/td*TimeSpan.TicksPerSecond > 25.0d)
                {
                    //SendMovePlayer();
                    return;
                }
            }

            //bool useAntiCheat = false;
            //if (useAntiCheat)
            //{
            //	long td = DateTime.UtcNow.Ticks - LastUpdatedTime.Ticks;
            //	if (GameMode == GameMode.Survival
            //		&& HealthManager.CooldownTick == 0
            //		&& td > 49*TimeSpan.TicksPerMillisecond
            //		&& td < 500*TimeSpan.TicksPerMillisecond
            //		&& Level.SpawnPoint.DistanceTo(new BlockCoordinates(KnownPosition)) > 2.0
            //		)
            //	{
            //		double horizSpeed;
            //		{
            //			// Speed in the xz plane

            //			Vector3 origin = new Vector3(KnownPosition.X, 0, KnownPosition.Z);
            //			double distanceTo = origin.DistanceTo(new Vector3(message.x, 0, message.z));
            //			horizSpeed = distanceTo/td*TimeSpan.TicksPerSecond;
            //			if (horizSpeed > 11.0d)
            //			{
            //				//Level.BroadcastTextMessage(string.Format("{0} spead cheating {3:##.##}m/s {1:##.##}m {2}ms", Username, distanceTo, (int) ((double) td/TimeSpan.TicksPerMillisecond), horizSpeed), type: MessageType.Raw);
            //				AddPopup(new Popup
            //				{
            //					MessageType = MessageType.Tip,
            //					Message = string.Format("{0} sprinting {3:##.##}m/s {1:##.##}m {2}ms", Username, distanceTo, (int) ((double) td/TimeSpan.TicksPerMillisecond), horizSpeed),
            //					Duration = 1
            //				});

            //				LastUpdatedTime = DateTime.UtcNow;
            //				HealthManager.TakeHit(this, 1, DamageCause.Suicide);
            //				SendMovePlayer();
            //				return;
            //			}
            //		}

            //		double verticalSpeed;
            //		{
            //			// Speed in 3d
            //			double speedLimit = (message.y - 1.62) - KnownPosition.Y < 0 ? -70d : 6d;
            //			double distanceTo = (message.y - 1.62) - KnownPosition.Y;
            //			verticalSpeed = distanceTo/td*TimeSpan.TicksPerSecond;
            //			if (!(horizSpeed > 0) && Math.Abs(verticalSpeed) > Math.Abs(speedLimit))
            //			{
            //				//Level.BroadcastTextMessage(string.Format("{0} fly cheating {3:##.##}m/s {1:##.##}m {2}ms", Username, distanceTo, (int) ((double) td/TimeSpan.TicksPerMillisecond), verticalSpeed), type: MessageType.Raw);
            //				AddPopup(new Popup
            //				{
            //					MessageType = MessageType.Tip,
            //					Message = string.Format("{3:##.##}m/s {1:##.##}m {2}ms", Username, distanceTo, (int) ((double) td/TimeSpan.TicksPerMillisecond), verticalSpeed),
            //					Duration = 1
            //				});

            //				LastUpdatedTime = DateTime.UtcNow;
            //				HealthManager.TakeHit(this, 1, DamageCause.Suicide);
            //				//SendMovePlayer();
            //				return;
            //			}
            //		}
            //		AddPopup(new Popup
            //		{
            //			MessageType = MessageType.Tip,
            //			Message = string.Format("Horiz: {0:##.##}m/s Vert: {1:##.##}m/s", horizSpeed, verticalSpeed),
            //			Duration = 1
            //		});
            //	}
            //}

            KnownPosition = new PlayerLocation
            {
                X = message.x,
                Y = message.y - 1.62f,
                Z = message.z,
                Pitch = message.pitch,
                Yaw = message.yaw,
                HeadYaw = message.headYaw
            };

            LastUpdatedTime = DateTime.UtcNow;

            //if (Level.Random.Next(0, 5) == 0)
            //{
            //	int data = 0;
            //	//data = (int) uint.Parse("FFFF0000", NumberStyles.HexNumber);
            //	data = Level.Random.Next((int) uint.Parse("FFFF0000", NumberStyles.HexNumber), (int) uint.Parse("FFFFFFFF", NumberStyles.HexNumber));

            //	Level.RelayBroadcast(new McpeLevelEvent
            //	{
            //		eventId = 0x4000 | 22,
            //		x = KnownPosition.X,
            //		//y = KnownPosition.Y - 1.62f,
            //		y = KnownPosition.Y - 1f,
            //		z = KnownPosition.Z,
            //		data = data
            //	});
            //}

            ThreadPool.QueueUserWorkItem(delegate(object state) { SendChunksForKnownPosition(); });
        }
Exemplo n.º 14
0
        /// <summary>
        ///     Handles the respawn.
        /// </summary>
        /// <param name="msg">The MSG.</param>
        private void HandleRespawn(McpeRespawn msg)
        {
            // reset all health states
            HealthManager.ResetHealth();

            // send teleport to spawn
            KnownPosition = new PlayerLocation
            {
                X = Level.SpawnPoint.X,
                Y = Level.SpawnPoint.Y,
                Z = Level.SpawnPoint.Z,
                Yaw = 91,
                Pitch = 28,
                HeadYaw = 91
            };

            SendSetHealth();

            SendPackage(new McpeAdventureSettings {flags = Level.IsSurvival ? 0x20 : 0x80});
            //SendPackage(new McpeAdventureSettings { flags = Level.IsSurvival ? 0x80 : 0x80 });

            SendPackage(new McpeContainerSetContent
            {
                windowId = 0,
                slotData = Inventory.Slots,
                hotbarData = Inventory.ItemHotbar
            });

            SendPackage(new McpeContainerSetContent
            {
                windowId = 0x78, // Armor windows ID
                slotData = Inventory.Armor,
                hotbarData = null
            });

            BroadcastSetEntityData();

            // Broadcast spawn to all
            Level.AddPlayer(this);

            SendMovePlayer();
        }
Exemplo n.º 15
0
        /// <summary>
        ///     Handles the move player.
        /// </summary>
        /// <param name="message">The message.</param>
        private void HandleMovePlayer(McpeMovePlayer message)
        {
            if (HealthManager.IsDead) return;

            long td = DateTime.UtcNow.Ticks - LastUpdatedTime.Ticks;
            if (GameMode == GameMode.Survival
                && HealthManager.CooldownTick == 0
                && td > 49*TimeSpan.TicksPerMillisecond
                && td < 500*TimeSpan.TicksPerMillisecond
                && Level.SpawnPoint.DistanceTo(new BlockCoordinates(KnownPosition)) > 2.0
                )
            {
                double horizSpeed;
                {
                    // Speed in the xz plane

                    Vector3 origin = new Vector3(KnownPosition.X, 0, KnownPosition.Z);
                    double distanceTo = origin.DistanceTo(new Vector3(message.x, 0, message.z));
                    horizSpeed = distanceTo/td*TimeSpan.TicksPerSecond;
                    if (horizSpeed > 11.0d)
                    {
                        Level.BroadcastTextMessage(string.Format("{0} spead cheating {3:##.##}m/s {1:##.##}m {2}ms", Username, distanceTo, (int) ((double) td/TimeSpan.TicksPerMillisecond), horizSpeed), type: MessageType.Chat);
                        AddPopup(new Popup
                        {
                            MessageType = MessageType.Chat,
                            Message = string.Format("{0} sprinting {3:##.##}m/s {1:##.##}m {2}ms", Username, distanceTo, (int) ((double) td/TimeSpan.TicksPerMillisecond), horizSpeed),
                            Duration = 1
                        });

                        LastUpdatedTime = DateTime.UtcNow;
                        HealthManager.TakeHit(this, 1, DamageCause.Suicide);
                        SendMovePlayer();
                        return;
                    }
                }

                double verticalSpeed;
                {
                    // Speed in 3d
                    double speedLimit = (message.y - 1.62) - KnownPosition.Y < 0 ? -70d : 6d;
                    double distanceTo = (message.y - 1.62) - KnownPosition.Y;
                    verticalSpeed = distanceTo/td*TimeSpan.TicksPerSecond;
                    if (!(horizSpeed > 0) && Math.Abs(verticalSpeed) > Math.Abs(speedLimit))
                    {
                        //Level.BroadcastTextMessage(string.Format("{0} fly cheating {3:##.##}m/s {1:##.##}m {2}ms", Username, distanceTo, (int) ((double) td/TimeSpan.TicksPerMillisecond), verticalSpeed), type: MessageType.Raw);
                        AddPopup(new Popup
                        {
                            MessageType = MessageType.Tip,
                            Message = string.Format("{3:##.##}m/s {1:##.##}m {2}ms", Username, distanceTo, (int) ((double) td/TimeSpan.TicksPerMillisecond), verticalSpeed),
                            Duration = 1
                        });

                        LastUpdatedTime = DateTime.UtcNow;
                        HealthManager.TakeHit(this, 1, DamageCause.Suicide);
                        //SendMovePlayer();
                        return;
                    }
                }
                AddPopup(new Popup
                {
                    MessageType = MessageType.Tip,
                    Message = string.Format("Horiz: {0:##.##}m/s Vert: {1:##.##}m/s", horizSpeed, verticalSpeed),
                    Duration = 1
                });
            }

            KnownPosition = new PlayerLocation
            {
                X = message.x,
                Y = message.y - 1.62f,
                Z = message.z,
                Pitch = message.pitch,
                Yaw = message.yaw,
                HeadYaw = message.headYaw
            };
            LastUpdatedTime = DateTime.UtcNow;

            if (IsBot) return;

            //if (Level.Random.Next(0, 5) == 0)
            //{
            //	int data = 0;
            //	//data = (int) uint.Parse("FFFF0000", NumberStyles.HexNumber);
            //	data = Level.Random.Next((int) uint.Parse("FFFF0000", NumberStyles.HexNumber), (int) uint.Parse("FFFFFFFF", NumberStyles.HexNumber));

            //	Level.RelayBroadcast(new McpeLevelEvent
            //	{
            //		eventId = 0x4000 | 22,
            //		x = KnownPosition.X,
            //		//y = KnownPosition.Y - 1.62f,
            //		y = KnownPosition.Y - 1f,
            //		z = KnownPosition.Z,
            //		data = data
            //	});
            //}

            SendChunksForKnownPosition();
        }
Exemplo n.º 16
0
        private Entity CheckEntityCollide(Vector3 position, Vector3 direction)
        {
            Ray2 ray = new Ray2
            {
                x = position,
                d = Vector3.Normalize(direction)
            };

            var players = Level.GetSpawnedPlayers().OrderBy(player => Vector3.Distance(position, player.KnownPosition.ToVector3()));
            foreach (var entity in players)
            {
                if (entity == Shooter) continue;

                if (Intersect(entity.GetBoundingBox(), ray))
                {
                    if (ray.tNear > direction.Length()) break;

                    Vector3 p = ray.x + new Vector3((float) ray.tNear)*ray.d;
                    KnownPosition = new PlayerLocation((float) p.X, (float) p.Y, (float) p.Z);
                    return entity;
                }
            }

            var entities = Level.Entities.Values.OrderBy(entity => Vector3.Distance(position, entity.KnownPosition.ToVector3()));
            foreach (Entity entity in entities)
            {
                if (entity == Shooter) continue;
                if (entity == this) continue;
                if (entity is Projectile) continue;

                if (Intersect(entity.GetBoundingBox(), ray))
                {
                    if (ray.tNear > direction.Length()) break;

                    Vector3 p = ray.x + new Vector3((float) ray.tNear)*ray.d;
                    KnownPosition = new PlayerLocation(p.X, p.Y, p.Z);
                    return entity;
                }
            }

            return null;
        }
Exemplo n.º 17
0
		public bool SetIntersectLocation(BoundingBox bbox, PlayerLocation location)
		{
			Ray ray = new Ray(location.ToVector3() - Velocity, Velocity.Normalize());
			double? distance = ray.Intersects(bbox);
			if (distance != null)
			{
				double dist = (double) distance - 0.1;
				Vector3 pos = ray.Position + (ray.Direction*dist);
				KnownPosition.X = (float) pos.X;
				KnownPosition.Y = (float) pos.Y;
				KnownPosition.Z = (float) pos.Z;
				return true;
			}

			return false;
		}
Exemplo n.º 18
0
        /// <summary>
        ///     Handles the specified package.
        /// </summary>
        /// <param name="message">The package.</param>
        /// <param name="senderEndpoint">The sender's endpoint.</param>
        private void HandlePackage(Package message, IPEndPoint senderEndpoint)
        {
            if (typeof (McpeBatch) == message.GetType())
            {
                McpeBatch batch = (McpeBatch) message;

                var messages = new List<Package>();

                // Get bytes
                byte[] payload = batch.payload;
                // Decompress bytes

                MemoryStream stream = new MemoryStream(payload);
                if (stream.ReadByte() != 0x78)
                {
                    throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
                }
                stream.ReadByte();
                using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
                {
                    // Get actual package out of bytes
                    MemoryStream destination = new MemoryStream();
                    defStream2.CopyTo(destination);
                    byte[] internalBuffer = destination.ToArray();
                    messages.Add(PackageFactory.CreatePackage(internalBuffer[0], internalBuffer) ?? new UnknownPackage(internalBuffer[0], internalBuffer));
                }
                foreach (var msg in messages)
                {
                    HandlePackage(msg, senderEndpoint);
                }
                return;
            }

            TraceReceive(message);

            if (typeof (UnknownPackage) == message.GetType())
            {
                return;
            }

            if (typeof (McpeDisconnect) == message.GetType())
            {
                McpeDisconnect msg = (McpeDisconnect) message;
                Log.Debug(msg.message);
                StopServer();
                return;
            }

            if (typeof (ConnectedPing) == message.GetType())
            {
                ConnectedPing msg = (ConnectedPing) message;
                SendConnectedPong(msg.sendpingtime);
                return;
            }

            if (typeof (McpeFullChunkData) == message.GetType())
            {
                McpeFullChunkData msg = (McpeFullChunkData) message;
                ChunkColumn chunk = ClientUtils.DecocedChunkColumn(msg.chunkData);
                if (chunk != null)
                {
                    Log.DebugFormat("Chunk X={0}", chunk.x);
                    Log.DebugFormat("Chunk Z={0}", chunk.z);

                    ClientUtils.SaveChunkToAnvil(chunk);
                }
                return;
            }

            if (typeof (ConnectionRequestAccepted) == message.GetType())
            {
                Thread.Sleep(50);
                SendNewIncomingConnection();
                var t1 = new Timer(state => SendConnectedPing(), null, 2000, 5000);
                Thread.Sleep(50);
                SendLogin("Client12");
                return;
            }

            if (typeof (McpeSetSpawnPosition) == message.GetType())
            {
                McpeSetSpawnPosition msg = (McpeSetSpawnPosition) message;
                _spawn = new Vector3(msg.x, msg.y, msg.z);
                _level.SpawnX = (int) _spawn.X;
                _level.SpawnY = (int) _spawn.Y;
                _level.SpawnZ = (int) _spawn.Z;

                return;
            }

            if (typeof (McpeStartGame) == message.GetType())
            {
                McpeStartGame msg = (McpeStartGame) message;
                _entityId = msg.entityId;
                _spawn = new Vector3(msg.x, msg.y, msg.z);
                _level.LevelName = "Default";
                _level.Version = 19133;
                _level.GameType = msg.gamemode;

                ClientUtils.SaveLevel(_level);

                return;
            }

            if (typeof (McpeTileEvent) == message.GetType())
            {
                McpeTileEvent msg = (McpeTileEvent) message;
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Case 1: {0}", msg.case1);
                Log.DebugFormat("Case 2: {0}", msg.case2);
                return;
            }
            if (typeof (McpeAddEntity) == message.GetType())
            {
                McpeAddEntity msg = (McpeAddEntity) message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                Log.DebugFormat("Entity Type: {0}", msg.entityType);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Yaw: {0}", msg.yaw);
                Log.DebugFormat("Pitch: {0}", msg.pitch);
                Log.DebugFormat("Velocity X: {0}", msg.speedX);
                Log.DebugFormat("Velocity Y: {0}", msg.speedY);
                Log.DebugFormat("Velocity Z: {0}", msg.speedZ);
                Log.DebugFormat("Metadata: {0}", msg.metadata.ToString());
                Log.DebugFormat("Links count: {0}", msg.links);

                return;
            }
            if (typeof (McpeSetEntityData) == message.GetType())
            {
                McpeSetEntityData msg = (McpeSetEntityData) message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                MetadataDictionary metadata = msg.metadata;
                Log.DebugFormat("Metadata: {0}", metadata.ToString());
                return;
            }

            if (typeof (McpeMovePlayer) == message.GetType())
            {
                McpeMovePlayer msg = (McpeMovePlayer) message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);

                _currentLocation = new PlayerLocation(msg.x, msg.y + 10, msg.z);
                SendMcpeMovePlayer();
                return;
            }

            if (typeof (McpeUpdateBlock) == message.GetType())
            {
                McpeUpdateBlock msg = (McpeUpdateBlock) message;
                Log.DebugFormat("No of Blocks: {0}", msg.blocks.Count);
                return;
            }

            if (typeof (McpeLevelEvent) == message.GetType())
            {
                McpeLevelEvent msg = (McpeLevelEvent) message;
                Log.DebugFormat("Event ID: {0}", msg.eventId);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Data: {0}", msg.data);
                return;
            }
        }
Exemplo n.º 19
0
		public void SetPosition(PlayerLocation position, bool teleport = true)
		{
			KnownPosition = position;

			var package = McpeMovePlayer.CreateObject();
			package.entityId = 0;
			package.x = position.X;
			package.y = position.Y + 1.62f;
			package.z = position.Z;
			package.yaw = position.Yaw;
			package.headYaw = position.HeadYaw;
			package.pitch = position.Pitch;
			package.mode = (byte) (teleport ? 1 : 0);

			SendPackage(package);
		}
Exemplo n.º 20
0
        private bool IsInSolid(PlayerLocation playerPosition)
        {
            float y = playerPosition.Y + 1.62f;

            BlockCoordinates solidPos = new BlockCoordinates
            {
                X = (int) Math.Floor(playerPosition.X),
                Y = (int) Math.Floor(y),
                Z = (int) Math.Floor(playerPosition.Z)
            };

            var block = Entity.Level.GetBlock(solidPos);

            if (block == null) return false;

            return block.IsSolid;
        }
Exemplo n.º 21
0
		protected virtual void HandleMovePlayer(McpeMovePlayer message)
		{
			if (!IsSpawned || HealthManager.IsDead) return;

			lock (_moveSyncLock)
			{
				if (_lastPlayerMoveSequenceNUmber > message.DatagramSequenceNumber)
				{
					return;
				}
				_lastPlayerMoveSequenceNUmber = message.DatagramSequenceNumber;

				if (_lastOrderingIndex > message.OrderingIndex)
				{
					return;
				}
				_lastOrderingIndex = message.OrderingIndex;
			}

			if (!AcceptPlayerMove(message)) return;

			KnownPosition = new PlayerLocation
			{
				X = message.x, Y = message.y - 1.62f, Z = message.z, Pitch = message.pitch, Yaw = message.yaw, HeadYaw = message.headYaw
			};

			LastUpdatedTime = DateTime.UtcNow;

			ThreadPool.QueueUserWorkItem(delegate(object state) { SendChunksForKnownPosition(); });
		}
Exemplo n.º 22
0
 public BlockCoordinates(PlayerLocation location)
 {
     X = (int)Math.Floor(location.X);
     Y = (int)Math.Floor(location.Y);
     Z = (int)Math.Floor(location.Z);
 }
Exemplo n.º 23
0
 public Minecart(Level level, PlayerLocation position)
     : base(EntityType.Minecart, level)
 {
     KnownPosition = position;
 }
Exemplo n.º 24
0
        private void OnMcpeMovePlayer(Package message)
        {
            McpeMovePlayer msg = (McpeMovePlayer) message;
            //Log.DebugFormat("McpeMovePlayer Entity ID: {0}", msg.entityId);

            CurrentLocation = new PlayerLocation(msg.x, msg.y + 10, msg.z);
            SendMcpeMovePlayer();
        }
Exemplo n.º 25
0
 public double DistanceTo(PlayerLocation other)
 {
     return(Math.Sqrt(Square(other.X - X) +
                      Square(other.Y - Y) +
                      Square(other.Z - Z)));
 }
Exemplo n.º 26
0
 public double DistanceTo(PlayerLocation other)
 {
     return Math.Sqrt(Square(other.X - X) +
                      Square(other.Y - Y) +
                      Square(other.Z - Z));
 }
Exemplo n.º 27
0
        public void Warp(Player player, string warp)
        {
            float x;
            float y;
            float z;

            switch (warp)
            {
                case "sg1":
                    x = 137;
                    y = 20;
                    z = 431;
                    break;
                case "sg2":
                    x = 682;
                    y = 20;
                    z = 324;
                    break;
                case "sg3":
                    x = 685;
                    y = 20;
                    z = -119;
                    break;
                default:
                    return;
            }

            var playerLocation = new PlayerLocation
            {
                X = x,
                Y = y,
                Z = z,
                Yaw = 91,
                Pitch = 28,
                HeadYaw = 91
            };

            ThreadPool.QueueUserWorkItem(delegate(object state) { player.SpawnLevel(player.Level, playerLocation); }, null);

            //player.Level.BroadcastMessage(string.Format("{0} teleported to coordinates {1},{2},{3}.", player.Username, x, y, z), type: MessageType.Raw);
        }
Exemplo n.º 28
0
		private Entity CheckEntityCollide(Vector3 position, Vector3 direction)
		{
			var players = Level.GetSpawnedPlayers().OrderBy(player => position.DistanceTo(player.KnownPosition.ToVector3()));
			Ray2 ray = new Ray2
			{
				x = position,
				d = direction.Normalize()
			};

			foreach (var entity in players)
			{
				if (entity == Shooter) continue;

				if (Intersect(entity.GetBoundingBox(), ray))
				{
					if (ray.tNear < direction.Distance) break;

					Vector3 p = ray.x + ray.tNear*ray.d;
					KnownPosition = new PlayerLocation((float) p.X, (float) p.Y, (float) p.Z);
					return entity;
				}
			}

			var entities = Level.Entities.Values.OrderBy(entity => position.DistanceTo(entity.KnownPosition.ToVector3()));
			foreach (Entity entity in entities)
			{
				if (entity == Shooter) continue;
				if (entity == this) continue;

				if (Intersect(entity.GetBoundingBox(), ray))
				{
					if (ray.tNear < direction.Distance) break;

					Vector3 p = ray.x + ray.tNear*ray.d;
					KnownPosition = new PlayerLocation((float) p.X, (float) p.Y, (float) p.Z);
					return entity;
				}
			}

			return null;
		}
Exemplo n.º 29
0
 public ChunkCoordinates(PlayerLocation location)
 {
     X = ((int)Math.Floor(location.X)) >> 4;
     Z = ((int)Math.Floor(location.Z)) >> 4;
 }
Exemplo n.º 30
0
		private bool CheckBlockCollide(PlayerLocation location)
		{
			var bbox = GetBoundingBox();
			var pos = location.ToVector3();

			var coords = new BlockCoordinates(
				(int) Math.Floor(KnownPosition.X),
				(int) Math.Floor((bbox.Max.Y + bbox.Min.Y)/2.0),
				(int) Math.Floor(KnownPosition.Z));

			Dictionary<double, Block> blocks = new Dictionary<double, Block>();

			for (int x = -1; x < 2; x++)
			{
				for (int z = -1; z < 2; z++)
				{
					for (int y = -1; y < 2; y++)
					{
						Block block = Level.GetBlock(coords.X + x, coords.Y + y, coords.Z + z);
						if (block is Air) continue;

						BoundingBox blockbox = block.GetBoundingBox() + 0.3;
						if (blockbox.Intersects(GetBoundingBox()))
						{
							//if (!blockbox.Contains(KnownPosition.ToVector3())) continue;

							if (block is FlowingLava || block is StationaryLava)
							{
								HealthManager.Ignite(1200);
								continue;
							}

							if (!block.IsSolid) continue;

							blockbox = block.GetBoundingBox();

							var midPoint = blockbox.Min + 0.5;
							blocks.Add((pos - Velocity).DistanceTo(midPoint), block);
						}
					}
				}
			}

			if (blocks.Count == 0) return false;

			var firstBlock = blocks.OrderBy(pair => pair.Key).First().Value;

			BoundingBox boundingBox = firstBlock.GetBoundingBox();
			if (!SetIntersectLocation(boundingBox, KnownPosition))
			{
				// No real hit
				return false;
			}

			// Use to debug hits, makes visual impressions (can be used for paintball too)
			var substBlock = new Stone {Coordinates = firstBlock.Coordinates};
			Level.SetBlock(substBlock);
			// End debug block

			Velocity = Vector3.Zero;
			return true;
		}
Exemplo n.º 31
0
        private bool IsInWater(PlayerLocation playerPosition)
        {
            float y = playerPosition.Y + 1.62f;

            BlockCoordinates waterPos = new BlockCoordinates
            {
                X = (int) Math.Floor(playerPosition.X),
                Y = (int) Math.Floor(y),
                Z = (int) Math.Floor(playerPosition.Z)
            };

            var block = Entity.Level.GetBlock(waterPos);

            if (block == null || (block.Id != 8 && block.Id != 9)) return false;

            return y < Math.Floor(y) + 1 - ((1/9) - 0.1111111);
        }
Exemplo n.º 32
0
        /// <summary>
        ///     Handles the move player.
        /// </summary>
        /// <param name="message">The message.</param>
        private void HandleMovePlayer(McpeMovePlayer message)
        {
            if (HealthManager.IsDead) return;

            if (DateTime.UtcNow.Ticks - LastUpdatedTime.Ticks < 20000) return;

            KnownPosition = new PlayerLocation
            {
                X = message.x,
                Y = message.y - 1.62f,
                Z = message.z,
                Pitch = message.pitch,
                Yaw = message.yaw,
                HeadYaw = message.headYaw
            };

            LastUpdatedTime = DateTime.UtcNow;

            if (IsBot) return;

            //if (Level.Random.Next(0, 5) == 0)
            //{
            //	int data = 0;
            //	//data = (int) uint.Parse("FFFF0000", NumberStyles.HexNumber);
            //	data = Level.Random.Next((int) uint.Parse("FFFF0000", NumberStyles.HexNumber), (int) uint.Parse("FFFFFFFF", NumberStyles.HexNumber));

            //	Level.RelayBroadcast(new McpeLevelEvent
            //	{
            //		eventId = 0x4000 | 22,
            //		x = KnownPosition.X,
            //		//y = KnownPosition.Y - 1.62f,
            //		y = KnownPosition.Y - 1f,
            //		z = KnownPosition.Z,
            //		data = data
            //	});
            //}

            SendChunksForKnownPosition();
        }