Geyser/connector/src/main/java/org/geysermc/connector/entity/player/PlayerEntity.java

330 lines
15 KiB
Java
Raw Normal View History

2019-08-03 03:38:09 +00:00
/*
* Copyright (c) 2019-2021 GeyserMC. http://geysermc.org
2019-08-03 03:38:09 +00:00
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.entity.player;
2019-08-03 03:38:09 +00:00
import com.github.steveice10.mc.auth.data.GameProfile;
import com.github.steveice10.mc.protocol.data.game.entity.metadata.EntityMetadata;
import com.github.steveice10.mc.protocol.data.game.entity.metadata.Pose;
import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.math.vector.Vector3i;
2020-06-23 00:11:09 +00:00
import com.nukkitx.protocol.bedrock.data.AttributeData;
import com.nukkitx.protocol.bedrock.data.PlayerPermission;
import com.nukkitx.protocol.bedrock.data.command.CommandPermission;
import com.nukkitx.protocol.bedrock.data.entity.EntityData;
import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;
2020-06-23 00:11:09 +00:00
import com.nukkitx.protocol.bedrock.data.entity.EntityLinkData;
Scoreboard improvements (#1166) * Added a way to check if debug logging is enabled * Improved scoreboard performance * Include Teams in pps and return pending pps instead when higher then pps Some servers have a huge amount of score packets when the player logs in, but before this commit, only after the first high pps (packets per second) the ScoreboardUpdater will be used (after pending packets per second have been moved to packets per second). But this commit fixes that the ScoreboardUpdater can be used on the second that the pps is getting high. * Fixed team pre + suffix "null" issue and added threshold config option Fixed team pre + suffix "null" issue. When the prefix and/or suffix of a Team is null, "null" will be returned instead of null (Due to the way that MCProtocolLib is made and designed). This is fixed by simply checking if the prefix and/or suffix equal "null" and if that is the case, replace it with "". Added threshold option. Gave the person who is running Geyser an option to specify the first Scoreboard packets per second threshold to further improve performance by lowering the setting or decrease performance by relaxing the setting a bit. The value can't be higher then 250 (the second threshold), because it'll always choose the lowest threshold. * Forgot to bump config version * Small changes * Reverted version bump, changed Sponge config, changed FloodgateKeyLoader Reverted version bump Camotoy said that you only need to bump the config version if the change is breaking, the config version bump has been reverted. Changed Sponge config The Sponge config has been modified to look like the other platform configurations. Changed FloodgateKeyLoader * Changed default-locale and (remote) address as requested by Camotoy * Reduce bandwidth and a few final tweaks * Made the scoreboard-packet-threshold a bit higher due to improvements
2020-08-28 15:47:52 +00:00
import com.nukkitx.protocol.bedrock.packet.AddPlayerPacket;
import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;
import com.nukkitx.protocol.bedrock.packet.SetEntityLinkPacket;
import com.nukkitx.protocol.bedrock.packet.UpdateAttributesPacket;
2019-08-03 03:38:09 +00:00
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.LivingEntity;
import org.geysermc.connector.entity.living.animal.tameable.ParrotEntity;
2019-08-03 03:38:09 +00:00
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.chat.MessageTranslator;
import org.geysermc.connector.scoreboard.Team;
2019-08-03 03:38:09 +00:00
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
2019-08-03 06:51:05 +00:00
@Getter @Setter
public class PlayerEntity extends LivingEntity {
private GameProfile profile;
2019-08-03 06:51:05 +00:00
private UUID uuid;
private String username;
Fix Skin Caching and Fix Skin Restorer (#680) * Fix Skin Caching Changes: * Instead of caching a skin based upon the player we cached it based upon the textureURL. This means multiple players with the same skin will benefit from the cache and more importantly will mean a player changing their skin will not get a false cache hit. * This should fix all issues with SkinRestorer and will now correctly show the skin both to the player themselves and to other players Closes #518 * Remove duplicated code * Minimize playerlist updates Changes: * All async skin stuff will now just update skins and not be involved with sending the session to the player. This eliminates issues where the player list changes whilst an async task is occuring plus it means no invisible players while retrieving skin. * Fix bug when retrieving cached skin * When sending PlayerList packets ensure the skins have appropriate skinIds so the Bedrock client will cache hit/miss as needed * Make sure to add and remove player when setting skin if they do not belong on the playerlist * Make use of AuthData UUID when removing the player * Revert removal of checking if entity is valid when initialized This section is supposed to send all spawned entities in the java world to a player only after they've initialized. By removing this check it would also be sending entities that exist but are not spawned. * Optimizations Changes: * Check for duplicate requests based on textureURL instead of player ID * Don't use the PlayerSkinPacket. It duplicates the data sent in the PlayerListPacket and without it the players still get skin updates. * Support caching of skins to disk based on configuration variable If a skin is downloaded it will be saved to `cache/skins` using a base64 encoded filename of the textureUrl, if allowed by setting a non 0 value for the configuration variable `cache-skins` When reading a skin we try load it from a cache file first before trying to download it. We don't yet expire them but do update their last modification so we know which ones have been accessed. * Update `config.yml` with cache-skins directive, defaulting to disabled * Merge Fixes * Cache all images instead of just skins Changes: * Move the image caching from skins to where images may get downloaded so this also covers capes and anything else that uses the same method of image retrieval * Updated config value from `cache-skins` to `cache-images` * Updated cache location from `cache/skins` to `cache/images` * Images are stored in png format with a uuid. This may make debugging easier as they can be directly opened. * Implement cached image expiry If `cache-images` is set to a value greater than 0 then a scheduled task will occur once a day that will remove images with a modification date older than the value in days. * Force skin changes as trusted * Resolve PR queries * Fix signed int causing issues calculating expiry time for images * Reset Defaults to 0 and implement Google Timed Eviction cache for Images * Add memory cache for Capes Co-authored-by: Brendan Grieve <brendan.grieve@zepli.com.au> Co-authored-by: bundabrg <bundabrg@grieve.com.au>
2020-08-07 16:33:21 +00:00
private boolean playerList = true; // Player is in the player list
2019-08-03 03:38:09 +00:00
/**
* Saves the parrot currently on the player's left shoulder; otherwise null
*/
private ParrotEntity leftParrot;
/**
* Saves the parrot currently on the player's right shoulder; otherwise null
*/
private ParrotEntity rightParrot;
public PlayerEntity(GameProfile gameProfile, long entityId, long geyserId, Vector3f position, Vector3f motion, Vector3f rotation) {
super(entityId, geyserId, EntityType.PLAYER, position, motion, rotation);
2019-08-03 03:38:09 +00:00
profile = gameProfile;
uuid = gameProfile.getId();
username = gameProfile.getName();
// For the OptionalPack, set all bits as invisible by default as this matches Java Edition behavior
metadata.put(EntityData.MARK_VARIANT, 0xff);
2019-08-03 03:38:09 +00:00
}
@Override
public void spawnEntity(GeyserSession session) {
AddPlayerPacket addPlayerPacket = new AddPlayerPacket();
2019-08-03 06:51:05 +00:00
addPlayerPacket.setUuid(uuid);
addPlayerPacket.setUsername(username);
addPlayerPacket.setRuntimeEntityId(geyserId);
addPlayerPacket.setUniqueEntityId(geyserId);
addPlayerPacket.setPosition(position.sub(0, EntityType.PLAYER.getOffset(), 0));
addPlayerPacket.setRotation(getBedrockRotation());
addPlayerPacket.setMotion(motion);
2019-08-03 03:38:09 +00:00
addPlayerPacket.setHand(hand);
addPlayerPacket.getAdventureSettings().setCommandPermission(CommandPermission.NORMAL);
addPlayerPacket.getAdventureSettings().setPlayerPermission(PlayerPermission.MEMBER);
addPlayerPacket.setDeviceId("");
addPlayerPacket.setPlatformChatId("");
addPlayerPacket.getMetadata().putAll(metadata);
2019-08-03 06:51:05 +00:00
Merge entity mounts branch to master (#589) * Initial support for entity mounts* * This only works for viewing other players on mounts/vehicles. Currently, mounting on vehicles through Geyser with bedrock does not work at all, though, you can see other Java players on mounts just fine. * Fix Bedrock player mounting; add minecart offset * Remove debug code * Fix boat animation * Remove debug code * Add notice of possible steering flip * Add translator for PlayerInputPacket * Upload WIP code for BoatEntity.java * Add animation for rowing on Bedrock side * Clean up debug code, start on boat movement * Add notice about flying horses * Rename BedrockPlayerInputPacket.java to BedrockPlayerInputTranslator.java * Delete BedrockPlayerInputPacket.java * Use Translator Annotation again; Thanks to LegacyGamerHD * Upload ineffective mount-on-login code * Upload current changes with no debug code * Change case where applicable * Change Integer[] to int[]; Change schedule() to execute() * Don't use Thread.Sleep() and instead call itself again * Fix players not being linked on login/chunk load * Little changes * Minor improvements/fixes to boats * Remove empty file * Fix horse flying. * Various entity mounting fixes * Add mounting offsets for skeleton and zombie horses * Another round of entity mount-related fixes - Add offsets for skeleton and zombie horses (Thanks to tester DirtNasty) - Boats can now be placed in survival (Thanks again to tester DirtNasty) - Boats and minecarts can now shake * Add translating for ServerVehicleMovePacket * Cleaning up * More cleaning up * Add interactive tag support for mountable entities * Boats move far more nicely * Add horse heart visuals * Update interactive tags Co-authored-by: RednedEpic <redned235@gmail.com>
2020-05-23 21:39:17 +00:00
long linkedEntityId = session.getEntityCache().getCachedPlayerEntityLink(entityId);
if (linkedEntityId != -1) {
Entity linkedEntity = session.getEntityCache().getEntityByJavaId(linkedEntityId);
if (linkedEntity != null) {
addPlayerPacket.getEntityLinks().add(new EntityLinkData(linkedEntity.getGeyserId(), geyserId, EntityLinkData.Type.RIDER, false, false));
}
Merge entity mounts branch to master (#589) * Initial support for entity mounts* * This only works for viewing other players on mounts/vehicles. Currently, mounting on vehicles through Geyser with bedrock does not work at all, though, you can see other Java players on mounts just fine. * Fix Bedrock player mounting; add minecart offset * Remove debug code * Fix boat animation * Remove debug code * Add notice of possible steering flip * Add translator for PlayerInputPacket * Upload WIP code for BoatEntity.java * Add animation for rowing on Bedrock side * Clean up debug code, start on boat movement * Add notice about flying horses * Rename BedrockPlayerInputPacket.java to BedrockPlayerInputTranslator.java * Delete BedrockPlayerInputPacket.java * Use Translator Annotation again; Thanks to LegacyGamerHD * Upload ineffective mount-on-login code * Upload current changes with no debug code * Change case where applicable * Change Integer[] to int[]; Change schedule() to execute() * Don't use Thread.Sleep() and instead call itself again * Fix players not being linked on login/chunk load * Little changes * Minor improvements/fixes to boats * Remove empty file * Fix horse flying. * Various entity mounting fixes * Add mounting offsets for skeleton and zombie horses * Another round of entity mount-related fixes - Add offsets for skeleton and zombie horses (Thanks to tester DirtNasty) - Boats can now be placed in survival (Thanks again to tester DirtNasty) - Boats and minecarts can now shake * Add translating for ServerVehicleMovePacket * Cleaning up * More cleaning up * Add interactive tag support for mountable entities * Boats move far more nicely * Add horse heart visuals * Update interactive tags Co-authored-by: RednedEpic <redned235@gmail.com>
2020-05-23 21:39:17 +00:00
}
2019-08-03 06:51:05 +00:00
valid = true;
session.sendUpstreamPacket(addPlayerPacket);
2019-08-03 03:38:09 +00:00
}
public void sendPlayer(GeyserSession session) {
if (session.getEntityCache().getPlayerEntity(uuid) == null)
return;
if (session.getUpstream().isInitialized() && session.getEntityCache().getEntityByGeyserId(geyserId) == null) {
session.getEntityCache().spawnEntity(this);
} else {
spawnEntity(session);
}
}
@Override
public void moveAbsolute(GeyserSession session, Vector3f position, Vector3f rotation, boolean isOnGround, boolean teleported) {
setPosition(position);
setRotation(rotation);
setOnGround(isOnGround);
MovePlayerPacket movePlayerPacket = new MovePlayerPacket();
movePlayerPacket.setRuntimeEntityId(geyserId);
movePlayerPacket.setPosition(this.position);
movePlayerPacket.setRotation(getBedrockRotation());
movePlayerPacket.setOnGround(isOnGround);
movePlayerPacket.setMode(teleported ? MovePlayerPacket.Mode.TELEPORT : MovePlayerPacket.Mode.NORMAL);
if (teleported) {
movePlayerPacket.setTeleportationCause(MovePlayerPacket.TeleportationCause.UNKNOWN);
}
session.sendUpstreamPacket(movePlayerPacket);
if (leftParrot != null) {
leftParrot.moveAbsolute(session, position, rotation, true, teleported);
}
if (rightParrot != null) {
rightParrot.moveAbsolute(session, position, rotation, true, teleported);
}
}
@Override
public void moveRelative(GeyserSession session, double relX, double relY, double relZ, Vector3f rotation, boolean isOnGround) {
setRotation(rotation);
this.position = Vector3f.from(position.getX() + relX, position.getY() + relY, position.getZ() + relZ);
setOnGround(isOnGround);
MovePlayerPacket movePlayerPacket = new MovePlayerPacket();
movePlayerPacket.setRuntimeEntityId(geyserId);
movePlayerPacket.setPosition(position);
movePlayerPacket.setRotation(getBedrockRotation());
movePlayerPacket.setOnGround(isOnGround);
movePlayerPacket.setMode(MovePlayerPacket.Mode.NORMAL);
// If the player is moved while sleeping, we have to adjust their y, so it appears
// correctly on Bedrock. This fixes GSit's lay.
if (metadata.getFlags().getFlag(EntityFlag.SLEEPING)) {
Vector3i bedPosition = metadata.getPos(EntityData.BED_POSITION);
if (bedPosition != null && (bedPosition.getY() == 0 || bedPosition.distanceSquared(position.toInt()) > 4)) {
// Force the player movement by using a teleport
movePlayerPacket.setPosition(Vector3f.from(position.getX(), position.getY() - entityType.getOffset() + 0.2f, position.getZ()));
movePlayerPacket.setMode(MovePlayerPacket.Mode.TELEPORT);
movePlayerPacket.setTeleportationCause(MovePlayerPacket.TeleportationCause.UNKNOWN);
}
}
session.sendUpstreamPacket(movePlayerPacket);
if (leftParrot != null) {
leftParrot.moveRelative(session, relX, relY, relZ, rotation, true);
}
if (rightParrot != null) {
rightParrot.moveRelative(session, relX, relY, relZ, rotation, true);
}
}
@Override
public void updateHeadLookRotation(GeyserSession session, float headYaw) {
moveRelative(session, 0, 0, 0, Vector3f.from(rotation.getX(), rotation.getY(), headYaw), onGround);
MovePlayerPacket movePlayerPacket = new MovePlayerPacket();
movePlayerPacket.setRuntimeEntityId(geyserId);
movePlayerPacket.setPosition(position);
movePlayerPacket.setRotation(getBedrockRotation());
2020-06-23 00:11:09 +00:00
movePlayerPacket.setMode(MovePlayerPacket.Mode.HEAD_ROTATION);
session.sendUpstreamPacket(movePlayerPacket);
}
@Override
public void updatePositionAndRotation(GeyserSession session, double moveX, double moveY, double moveZ, float yaw, float pitch, boolean isOnGround) {
moveRelative(session, moveX, moveY, moveZ, yaw, pitch, isOnGround);
if (leftParrot != null) {
leftParrot.moveRelative(session, moveX, moveY, moveZ, yaw, pitch, isOnGround);
}
if (rightParrot != null) {
rightParrot.moveRelative(session, moveX, moveY, moveZ, yaw, pitch, isOnGround);
}
}
@Override
public void updateRotation(GeyserSession session, float yaw, float pitch, boolean isOnGround) {
super.updateRotation(session, yaw, pitch, isOnGround);
// Both packets need to be sent or else player head rotation isn't correctly updated
MovePlayerPacket movePlayerPacket = new MovePlayerPacket();
movePlayerPacket.setRuntimeEntityId(geyserId);
movePlayerPacket.setPosition(position);
movePlayerPacket.setRotation(getBedrockRotation());
movePlayerPacket.setOnGround(isOnGround);
2020-06-23 00:11:09 +00:00
movePlayerPacket.setMode(MovePlayerPacket.Mode.HEAD_ROTATION);
session.sendUpstreamPacket(movePlayerPacket);
if (leftParrot != null) {
leftParrot.updateRotation(session, yaw, pitch, isOnGround);
}
if (rightParrot != null) {
rightParrot.updateRotation(session, yaw, pitch, isOnGround);
}
}
@Override
public void setPosition(Vector3f position) {
super.setPosition(position.add(0, entityType.getOffset(), 0));
}
@Override
public void updateBedrockMetadata(EntityMetadata entityMetadata, GeyserSession session) {
super.updateBedrockMetadata(entityMetadata, session);
if (entityMetadata.getId() == 2) {
String username = this.username;
Component name = (Component) entityMetadata.getValue();
if (name != null) {
username = MessageTranslator.convertMessage(name);
}
Team team = session.getWorldCache().getScoreboard().getTeamFor(username);
if (team != null) {
String displayName = "";
if (team.isVisibleFor(session.getPlayerEntity().getUsername())) {
displayName = MessageTranslator.toChatColor(team.getColor()) + username;
displayName = team.getCurrentData().getDisplayName(displayName);
}
metadata.put(EntityData.NAMETAG, displayName);
}
}
// Extra hearts - is not metadata but an attribute on Bedrock
2021-05-20 02:24:11 +00:00
if (entityMetadata.getId() == 15) {
UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
attributesPacket.setRuntimeEntityId(geyserId);
// Setting to a higher maximum since plugins/datapacks can probably extend the Bedrock soft limit
attributesPacket.setAttributes(Collections.singletonList(
new AttributeData("minecraft:absorption", 0.0f, 1024f, (float) entityMetadata.getValue(), 0.0f)));
session.sendUpstreamPacket(attributesPacket);
}
2021-05-20 02:24:11 +00:00
if (entityMetadata.getId() == 17) {
// OptionalPack usage for toggling skin bits
// In Java Edition, a bit being set means that part should be enabled
// However, to ensure that the pack still works on other servers, we invert the bit so all values by default
// are true (0).
metadata.put(EntityData.MARK_VARIANT, ~((byte) entityMetadata.getValue()) & 0xff);
}
// Parrot occupying shoulder
2021-05-20 02:24:11 +00:00
if (entityMetadata.getId() == 19 || entityMetadata.getId() == 20) {
CompoundTag tag = (CompoundTag) entityMetadata.getValue();
boolean isLeft = entityMetadata.getId() == 19;
if (tag != null && !tag.isEmpty()) {
if ((isLeft && leftParrot != null) || (!isLeft && rightParrot != null)) {
// No need to update a parrot's data when it already exists
return;
}
// The parrot is a separate entity in Bedrock, but part of the player entity in Java
ParrotEntity parrot = new ParrotEntity(0, session.getEntityCache().getNextEntityId().incrementAndGet(),
EntityType.PARROT, position, motion, rotation);
parrot.spawnEntity(session);
parrot.getMetadata().put(EntityData.VARIANT, tag.get("Variant").getValue());
// Different position whether the parrot is left or right
float offset = isLeft ? 0.4f : -0.4f;
parrot.getMetadata().put(EntityData.RIDER_SEAT_POSITION, Vector3f.from(offset, -0.22, -0.1));
parrot.getMetadata().put(EntityData.RIDER_ROTATION_LOCKED, 1);
parrot.updateBedrockMetadata(session);
SetEntityLinkPacket linkPacket = new SetEntityLinkPacket();
EntityLinkData.Type type = isLeft ? EntityLinkData.Type.RIDER : EntityLinkData.Type.PASSENGER;
linkPacket.setEntityLink(new EntityLinkData(geyserId, parrot.getGeyserId(), type, false, false));
// Delay, or else spawned-in players won't get the link
// TODO: Find a better solution. This problem also exists with item frames
session.getConnector().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(linkPacket), 500, TimeUnit.MILLISECONDS);
if (isLeft) {
leftParrot = parrot;
} else {
rightParrot = parrot;
}
} else {
Entity parrot = isLeft ? leftParrot : rightParrot;
if (parrot != null) {
parrot.despawnEntity(session);
if (isLeft) {
leftParrot = null;
} else {
rightParrot = null;
}
}
}
}
}
@Override
protected void setDimensions(Pose pose) {
float height;
switch (pose) {
case SNEAKING -> height = 1.5f;
case FALL_FLYING, SPIN_ATTACK, SWIMMING -> height = 0.6f;
default -> {
super.setDimensions(pose);
return;
}
}
metadata.put(EntityData.BOUNDING_BOX_WIDTH, entityType.getWidth());
metadata.put(EntityData.BOUNDING_BOX_HEIGHT, height);
}
2019-08-03 03:38:09 +00:00
}