1
0
Fork 0
tcr/server/src/main/java/server/network/Player.java
2025-09-08 00:41:22 +02:00

3154 lines
116 KiB
Java
Executable file

package server.network;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import common.block.Block;
import common.block.artificial.BlockFence;
import common.block.artificial.BlockFenceGate;
import common.block.artificial.BlockWall;
import common.block.tech.InteractionObject;
import common.collect.Lists;
import common.dimension.Dimension;
import common.dimension.Space;
import common.effect.Effect;
import common.effect.StatusEffect;
import common.entity.Entity;
import common.entity.animal.EntityHorse;
import common.entity.item.EntityCamera;
import common.entity.item.EntityCamera.CameraType;
import common.entity.item.EntityItem;
import common.entity.item.EntityXp;
import common.entity.npc.Alignment;
import common.entity.npc.EntityCameraHolder;
import common.entity.npc.EntityHuman;
import common.entity.npc.EntityNPC;
import common.entity.npc.PlayerCharacter;
import common.entity.projectile.EntityArrow;
import common.entity.types.EntityLiving;
import common.init.BlockRegistry;
import common.init.Blocks;
import common.init.CraftingRegistry;
import common.init.EntityRegistry;
import common.init.Items;
import common.init.SoundEvent;
import common.inventory.Container;
import common.inventory.ContainerChest;
import common.inventory.ContainerEnchantment;
import common.inventory.ContainerEntityInventory;
import common.inventory.ContainerMerchant;
import common.inventory.ContainerTile;
import common.inventory.ContainerWorkbench;
import common.inventory.IInventory;
import common.inventory.InventoryBasic;
import common.inventory.Slot;
import common.item.Item;
import common.item.ItemControl;
import common.item.ItemStack;
import common.log.Log;
import common.net.util.concurrent.Future;
import common.net.util.concurrent.GenericFutureListener;
import common.network.IPlayer;
import common.network.NetConnection;
import common.network.NetHandler;
import common.network.Packet;
import common.packet.CPacketAction;
import common.packet.CPacketBreak;
import common.packet.CPacketCheat;
import common.packet.CPacketClick;
import common.packet.CPacketComplete;
import common.packet.CPacketForm;
import common.packet.CPacketInput;
import common.packet.CPacketKeepAlive;
import common.packet.CPacketMessage;
import common.packet.CPacketPlace;
import common.packet.CPacketPlayer;
import common.packet.CPacketSign;
import common.packet.CPacketSkin;
import common.packet.SPacketEntityTeleport;
import common.packet.SPacketEntityStatus;
import common.packet.SPacketEntityAttach;
import common.packet.SPacketEntityEffect;
import common.packet.SPacketRemoveEntityEffect;
import common.packet.SPacketSoundEffect;
import common.packet.SPacketOpenWindow;
import common.packet.SPacketCloseWindow;
import common.packet.SPacketSetSlot;
import common.packet.SPacketWindowItems;
import common.packet.SPacketWindowProperty;
import common.packet.SPacketConfirmTransaction;
import common.packet.SPacketSignEditorOpen;
import common.packet.SPacketPlayerAbilities;
import common.packet.SPacketTabComplete;
import common.packet.SPacketAnimation;
import common.packet.SPacketBlockChange;
import common.packet.SPacketCamera;
import common.packet.SPacketCharacterList;
import common.packet.SPacketChunkData;
import common.packet.SPacketDestroyEntities;
import common.packet.SPacketDisconnect;
import common.packet.SPacketDisplayForm;
import common.packet.SPacketKeepAlive;
import common.packet.SPacketMapChunkBulk;
import common.packet.SPacketMessage;
import common.packet.SPacketPlayerPosLook;
import common.packet.SPacketServerTick;
import common.packet.SPacketSetExperience;
import common.packet.SPacketSkin;
import common.packet.SPacketTrades;
import common.packet.SPacketUpdateHealth;
import common.packet.CPacketAction.Action;
import common.packet.SPacketMessage.Type;
import common.tags.TagObject;
import common.tileentity.TileEntity;
import common.tileentity.TileEntityChest;
import common.tileentity.Device;
import common.tileentity.TileEntitySign;
import common.util.LocalPos;
import common.util.BoundingBox;
import common.util.ExtMath;
import common.util.Facing;
import common.util.IntHashMap;
import common.util.MutablePos;
import common.util.PortalType;
import common.util.Position;
import common.util.Color;
import common.util.Equipment;
import common.util.Vec3i;
import common.util.GlobalPos;
import common.vars.Vars;
import common.village.MerchantRecipeList;
import common.world.BlockArray;
import common.world.State;
import common.world.World;
import server.Server;
import server.clipboard.Mat2i;
import server.clipboard.ClipboardBlock;
import server.clipboard.ClipboardPlacer;
import server.clipboard.RotationRegistry;
import server.clipboard.RotationValue;
import server.command.Executor;
import server.init.UniverseRegistry;
import server.util.ChunkPos;
import server.util.Form;
import server.vars.SVars;
import server.world.ChunkServer;
import server.world.Region;
import server.world.WorldServer;
import server.worldgen.layer.BiomeGenerator;
public class Player extends User implements Executor, IPlayer
{
private static enum EditAction {
SELECT("Auswahlmodus"), COPYPASTE("Kopiermodus"), TRANSFORM("Drehmodus");
private final String display;
private EditAction(String display) {
this.display = display;
}
}
private final NetConnection connection;
private final Server server;
private final IntHashMap<Short> transactions = new IntHashMap();
private final List<TagObject> characters = Lists.newArrayList();
private EntityNPC entity;
private int tickTime;
private int lastMoved;
private int pingKey;
private int selected = -1;
private int lastSelected = -1;
private long lastPingTime = System.nanoTime() / 1000000L;
private int lastSentPingPacket;
private double lastPosX;
private double lastPosY;
private double lastPosZ;
private boolean hasMoved = true;
private boolean charEditor = true;
private Form form;
private int ping;
private boolean profiling;
private int selectionDim = Integer.MIN_VALUE;
private ClipboardBlock[][][] clipboard;
private int rotation;
private boolean flipX;
private boolean flipZ;
private LocalPos selPos1;
private LocalPos selPos2;
private Vec3i selOffset;
private EditAction edit = EditAction.SELECT;
private LocalPos startPos = LocalPos.ORIGIN;
private LocalPos removingPos = LocalPos.ORIGIN;
private boolean isDestroyingBlock;
private boolean receivedFinishDiggingPacket;
private int initialDamage;
private int curblockDamage;
private int initialBlockDamage;
private int durabilityRemainingOnBlock = -1;
private boolean isChangingQuantityOnly;
private int respawnTimer;
private double managedPosX;
private double managedPosZ;
private float combinedHealth = Float.MIN_VALUE;
private float lastHealth = -1.0E8F;
private int lastExperience = -99999999;
private int currentWindowId;
private int currentFormId;
private int itemUseCooldown;
private int pointedEntity;
private LocalPos pointedPosition;
private final List<ChunkPos> loadedChunks = new LinkedList<ChunkPos>();
private final List<Integer> destroyedItemsNetCache = new LinkedList<Integer>();
private Position forcedPos;
private Executor forcedExec;
private Position deathPos;
private Position teleportPos;
private Position lastDeathPos;
private Position lastTeleportPos;
private EntityCamera camera;
public Player(Server server, NetConnection connection, String user)
{
super(user);
this.server = server;
this.connection = connection;
// this.local = connection.isLocalChannel();
}
public EntityNPC createPlayer(WorldServer world, String id) {
this.entity = (EntityNPC)EntityRegistry.createEntityByName(id, world);
if(this.entity == null)
this.entity = new EntityHuman(world);
this.entity.setServerPlayer(this);
this.isDestroyingBlock = false;
this.receivedFinishDiggingPacket = false;
this.initialDamage = 0;
this.curblockDamage = 0;
this.initialBlockDamage = 0;
this.durabilityRemainingOnBlock = -1;
this.managedPosX = 0.0;
this.managedPosZ = 0.0;
this.combinedHealth = Float.MIN_VALUE;
this.lastHealth = -1.0E8F;
this.lastExperience = -99999999;
this.currentWindowId = 0;
this.loadedChunks.clear();
// this.destroyedItemsNetCache.clear();
this.itemUseCooldown = 0;
return this.entity;
}
public void update()
{
++this.tickTime;
if (this.tickTime - this.lastSentPingPacket > 40)
{
this.lastSentPingPacket = this.tickTime;
this.lastPingTime = System.nanoTime() / 1000000L;
this.pingKey = (int)this.lastPingTime;
this.sendPacket(new SPacketKeepAlive(this.pingKey));
}
if(this.isAdmin() && this.profiling)
this.sendPacket(new SPacketServerTick((int)this.server.getLastTick()));
if(this.respawnTimer > 0) {
if(--this.respawnTimer == 0) {
this.respawnPlayer();
}
}
if(this.itemUseCooldown > 0)
--this.itemUseCooldown;
if(this.camera != null)
this.camera.onUpdate();
}
public boolean isOnline() {
return true;
}
public void onEntityDeath() {
this.deathPos = this.entity.getPos();
this.entity.sendDeathMessage();
if (!Vars.keepInventory && Vars.playerDrop)
{
for (int i = 0; i < this.entity.getSizeInventory(); ++i)
{
ItemStack stack = this.entity.getStackInSlot(i);
if (stack != null)
{
this.entity.dropItem(stack, true, false);
this.entity.setInventorySlotContents(i, null);
}
}
}
if(Vars.skullDrop) {
ItemStack stack = new ItemStack(Items.skull);
this.entity.dropItem(stack, true, false);
}
EntityLiving entitylivingbase = this.entity.getAttackingEntity();
if (entitylivingbase != null)
{
// EntityEggInfo entitylist$entityegginfo = (EntityEggInfo)EntityRegistry.SPAWN_EGGS.get(EntityRegistry.getEntityString(entitylivingbase));
//
// if (entitylist$entityegginfo != null)
// {
// this.entity.triggerAchievement(entitylist$entityegginfo.killedByStat);
// }
if(entitylivingbase.isPlayer())
((EntityNPC)entitylivingbase).connection.addToPlayerScore(this.entity);
}
// this.entity.triggerAchievement(StatRegistry.deathsStat);
// this.setListsDirty();
// this.removeStat(StatRegistry.timeSinceDeathStat);
this.entity.resetCombat();
if(SVars.respawnTime > 0)
this.respawnTimer = ExtMath.clampi(SVars.respawnTime, 2, 20);
}
public boolean isInEditor() {
return this.charEditor;
}
public EntityNPC getPresentEntity() {
return this.charEditor ? null : this.entity;
}
public EntityNPC getEntity() {
return this.entity;
}
// public boolean isLocal() {
// return this.local;
// }
public int getLatency() {
return this.ping;
}
public boolean setCamera(Dimension dim, double x, double y, double z, float yaw, float pitch, int radius, float speed, CameraType type, boolean fixed) {
if(this.charEditor || this.characters.isEmpty() || this.selected < 0 || this.lastSelected >= 0)
return false;
this.lastDeathPos = this.deathPos;
this.lastTeleportPos = this.teleportPos;
String name = this.entity.getCustomNameTag();
TagObject tag = this.server.swapPlayer(this, null, EntityCameraHolder.class);
this.characters.set(this.selected, tag);
this.lastSelected = this.selected;
this.selected = this.characters.size();
this.characters.add(new TagObject());
WorldServer world = this.server.getWorld(dim);
world = world == null ? this.server.getSpace() : world;
this.entity.teleport(x, y, z, yaw, pitch, world);
this.entity.setNoclip(true);
this.entity.setCustomNameTag("Kamera von " + name);
this.teleportPos = this.deathPos = null;
this.camera = new EntityCamera(this.entity.worldObj, x, y, z, yaw, pitch, radius, speed, type, fixed);
this.sendPacket(new SPacketCamera(this.camera));
return true;
}
public boolean unsetCamera() {
if(this.charEditor || this.lastSelected >= this.characters.size() || this.lastSelected < 0)
return false;
this.server.swapPlayer(this, this.characters.get(this.selected = this.lastSelected), null);
this.characters.removeLast();
this.lastSelected = -1;
this.deathPos = this.lastDeathPos;
this.teleportPos = this.lastTeleportPos;
this.camera = null;
this.sendPacket(new SPacketCamera(null));
return true;
}
public void addSelfToInternalCraftingInventory()
{
this.entity.openContainer.onCraftGuiOpened(this);
}
public void addToPlayerScore(EntityLiving entity)
{
// if (entity.isPlayer())
// {
// this.entity.triggerAchievement(StatRegistry.playerKillsStat);
// }
// else
// {
// this.entity.triggerAchievement(StatRegistry.killsStat);
// }
}
private void sendTileEntityUpdate(TileEntity p_147097_1_)
{
if (p_147097_1_ != null)
{
Packet packet = p_147097_1_.getDescriptionPacket();
if (packet != null)
{
this.sendPacket(packet);
}
}
}
public void handleFalling(double p_71122_1_, boolean p_71122_3_)
{
int i = ExtMath.floord(this.entity.posX);
int j = ExtMath.floord(this.entity.posY - 0.20000000298023224D);
int k = ExtMath.floord(this.entity.posZ);
LocalPos blockpos = new LocalPos(i, j, k);
Block block = this.entity.worldObj.getState(blockpos).getBlock();
if (block == Blocks.air)
{
Block block1 = this.entity.worldObj.getState(blockpos.down()).getBlock();
if (block1 instanceof BlockFence || block1 instanceof BlockWall || block1 instanceof BlockFenceGate)
{
blockpos = blockpos.down();
block = this.entity.worldObj.getState(blockpos).getBlock();
}
}
this.entity.updateEntityFall(p_71122_1_, p_71122_3_, block, blockpos);
}
private int getNextWindowId()
{
this.currentWindowId = this.currentWindowId % 100 + 1;
return this.currentWindowId;
}
private void getNextFormId()
{
this.currentFormId = this.currentFormId % 100 + 1;
}
public void updateMouseItem()
{
if (!this.isChangingQuantityOnly)
{
this.sendPacket(new SPacketSetSlot(-1, -1, this.entity.getMouseItem()));
}
}
private void setEntityActionState(float strafe, float forward, boolean jumping, boolean sneaking, boolean camera)
{
if(camera) {
if(this.camera != null)
this.camera.setMovement(strafe, forward, jumping, sneaking);
}
else if (this.entity.vehicle != null)
{
if (strafe >= -1.0F && strafe <= 1.0F)
{
this.entity.moveStrafe = strafe;
}
if (forward >= -1.0F && forward <= 1.0F)
{
this.entity.moveForward = forward;
}
this.entity.setJumping(jumping);
this.entity.setSneaking(sneaking);
}
}
public void setPlayerHealthUpdated()
{
this.lastHealth = -1.0E8F;
}
public void copyPlayer(EntityNPC oldPlayer)
{
this.lastExperience = -1;
this.lastHealth = -1.0F;
if(Vars.keepInventory) {
for(int z = 0; z < this.entity.getSizeInventory(); z++) {
this.entity.setInventorySlotContents(z, ItemStack.copy(oldPlayer.getStackInSlot(z)));
}
this.entity.setSelectedIndex(oldPlayer.getSelectedIndex());
}
this.entity.experienceLevel = oldPlayer.experienceLevel;
this.entity.experienceTotal = oldPlayer.experienceTotal;
this.entity.experience = oldPlayer.experience;
this.entity.setEnchSeed(oldPlayer.getEnchSeed());
this.entity.setWarpChest(oldPlayer.getWarpChest());
this.entity.setSkin(oldPlayer.getSkin());
this.entity.setHeight(oldPlayer.getHeight());
this.entity.setCustomNameTag(oldPlayer.getCustomNameTag());
this.entity.setAlignment(oldPlayer.getAlignment());
this.entity.setAttackDamageBase(oldPlayer.getAttackDamageBase());
this.entity.setSpeedBase(oldPlayer.getSpeedBase());
this.entity.setMaxHealth(oldPlayer.getMaxHealth());
this.entity.setMaxMana(oldPlayer.getMaxMana());
}
public void removeEntity(Entity p_152339_1_)
{
if (p_152339_1_.isPlayer())
{
this.sendPacket(new SPacketDestroyEntities(p_152339_1_.getId()));
}
else
{
this.destroyedItemsNetCache.add(Integer.valueOf(p_152339_1_.getId()));
}
}
// public void sendStats() {
// long upd = this.server.getTickCounter();
// Map<StatBase, Integer> map = Maps.<StatBase, Integer>newHashMap();
//// if(upd - this.lastStatsUpdate > 300) {
//// this.lastStatsUpdate = upd;
// for(StatBase stat : this.statsQueue) {
// map.put(stat, this.getStat(stat));
// }
// this.statsQueue.clear();
//// }
// this.sendPacket(new S37PacketStatistics(map));
// }
// public void initializeStats() {
// for(StatBase stat : this.stats.keySet()) {
// this.statsQueue.add(stat);
// }
// }
//
// private void setStat(StatBase stat, int value) {
// this.stats.put(stat, value);
// this.statsQueue.add(stat);
// }
//
// private int getStat(StatBase stat) {
// Integer i = this.stats.get(stat);
// return i == null ? 0 : i.intValue();
// }
public void sendPlayerAbilities()
{
if (this.entity != null)
{
this.sendPacket(new SPacketPlayerAbilities(this.entity));
this.entity.updateEffectMeta();
}
}
public void addConsole(String msg) {
this.sendPacket(new SPacketMessage(msg, Type.CONSOLE));
}
public void addConsole(String format, Object... args) {
this.sendPacket(new SPacketMessage(String.format(format, args), Type.CONSOLE));
}
public void addChat(String msg) {
this.sendPacket(new SPacketMessage(msg, Type.CHAT));
}
public void addChat(String format, Object... args) {
this.sendPacket(new SPacketMessage(String.format(format, args), Type.CHAT));
}
public void addFeed(String msg) {
this.sendPacket(new SPacketMessage(msg, Type.FEED));
}
public void addFeed(String format, Object... args) {
this.sendPacket(new SPacketMessage(String.format(format, args), Type.FEED));
}
public void addHotbar(String msg) {
this.sendPacket(new SPacketMessage(msg, Type.HOTBAR));
}
public void addHotbar(String format, Object... args) {
this.sendPacket(new SPacketMessage(String.format(format, args), Type.HOTBAR));
}
private WorldServer getEntityWorld() {
return (WorldServer)this.entity.getServerWorld();
}
public void sendPickupMessage(Entity entity, int amount) {
if(entity instanceof EntityItem)
if(amount == 1)
this.addFeed(Color.DARK_GREEN + "* %s aufgelesen",
((EntityItem)entity).getEntityItem().getColoredName(Color.DARK_GREEN));
else
this.addFeed(Color.DARK_GREEN + "* %d %s aufgelesen", amount,
((EntityItem)entity).getEntityItem().getColoredName(Color.DARK_GREEN));
else if(entity instanceof EntityArrow)
this.addFeed(Color.DARK_GREEN + "* Pfeil aufgelesen", amount);
else if(entity instanceof EntityXp)
this.addFeed(Color.GREEN + "* %d Erfahrung gesammelt", amount);
}
public void sendThrowMessage(ItemStack stack) {
if(stack.getSize() == 1)
this.addFeed(Color.DARK_RED + "* %s weg geworfen",
stack.getColoredName(Color.DARK_RED));
else
this.addFeed(Color.DARK_RED + "* %d %s weg geworfen", stack.getSize(),
stack.getColoredName(Color.DARK_RED));
}
public void readTags(TagObject tag) {
this.selected = tag.getInt("selected");
List<TagObject> list = tag.getList("characters");
for(int z = 0; z < list.size(); z++) {
this.characters.add(list.get(z));
}
this.selected = Math.min(this.selected, this.characters.size() - 1);
this.charEditor = this.selected < 0;
}
public void writeTags(TagObject tag) {
if(!this.characters.isEmpty()) {
tag.setInt("selected", this.lastSelected >= 0 ? this.lastSelected : this.selected);
List<TagObject> list = Lists.newArrayList();
for(TagObject etag : this.characters) {
list.add(etag);
}
if(this.lastSelected >= 0)
list.removeLast();
tag.setList("characters", list);
}
}
public void resetLastExperience()
{
this.lastExperience = -1;
}
public void travelToDimension(Dimension dimensionId, LocalPos pos, float yaw, float pitch, PortalType portal)
{
if(this.camera != null)
return;
this.server.transferToDimension(this.entity, dimensionId, pos, yaw, pitch, portal);
this.lastExperience = -1;
this.lastHealth = -1.0F;
}
public void teleport(double x, double y, double z, float yaw, float pitch, Dimension dimension) {
if(this.camera != null)
this.unsetCamera();
this.teleportPos = this.entity.getPos();
x = ExtMath.clampd(x, -World.MAX_SIZE + 1, World.MAX_SIZE - 1);
z = ExtMath.clampd(z, -World.MAX_SIZE + 1, World.MAX_SIZE - 1);
// this.setLastTeleport(this.getLocation());
this.entity.unmount();
// this.mountEntity(null);
if(this.entity.worldObj.dimension != dimension)
this.travelToDimension(dimension, new LocalPos(x, y, z), yaw, pitch, null);
this.setPlayerLocation(x, y, z, yaw, pitch);
this.entity.setRotationYawHead(yaw);
}
public void onItemPickup(Entity entity, int amount)
{
this.entity.openContainer.detectAndSendChanges();
if(!entity.dead)
this.sendPickupMessage(entity, amount);
}
public void mountEntity(Entity entityIn)
{
this.sendPacket(new SPacketEntityAttach(0, this.entity, this.entity.vehicle));
this.setPlayerLocation(this.entity.posX, this.entity.posY, this.entity.posZ, this.entity.rotYaw, this.entity.rotPitch);
}
public void show(Object object)
{
if(object == null || this.entity.openContainer != this.entity.inventoryContainer) {
this.sendPacket(new SPacketCloseWindow(this.entity.openContainer.windowId));
this.entity.openContainer.onContainerClosed(this.entity);
this.entity.openContainer = this.entity.inventoryContainer;
if(object == null)
return;
}
if(object instanceof TileEntitySign sign) {
sign.setPlayer(this.entity);
this.sendPacket(new SPacketSignEditorOpen(sign.getPos()));
return;
}
else if(object instanceof EntityNPC npc && !npc.isPlayer()) {
this.getNextWindowId();
this.entity.openContainer = new ContainerMerchant(this.entity, npc, this.entity.worldObj);
}
else if(object instanceof Entity entity && !entity.isPlayer()) {
InventoryBasic inv = entity.getEntityInventory();
this.sendPacket(new SPacketOpenWindow(this.getNextWindowId(), entity.getId(), inv.getSizeInventory()));
this.entity.openContainer = new ContainerEntityInventory(this.entity, inv, entity);
}
else if (object instanceof Device device)
{
this.sendPacket(new SPacketOpenWindow(this.getNextWindowId(), device.getPos(), device.getSizeInventory()));
this.entity.openContainer = new ContainerTile(this.entity, device, device);
}
else if (object instanceof TileEntityChest chest)
{
this.sendPacket(new SPacketOpenWindow(this.getNextWindowId(), chest.getBlock(), chest.getSizeInventory()));
this.entity.openContainer = new ContainerChest(this.entity, chest);
}
else if (object instanceof InteractionObject obj)
{
this.sendPacket(new SPacketOpenWindow(this.getNextWindowId(), obj.getBlock(), 0));
this.entity.openContainer = obj.createContainer(this.entity);
}
else {
return;
}
this.entity.openContainer.windowId = this.currentWindowId;
this.entity.openContainer.onCraftGuiOpened(this);
if(object instanceof EntityNPC npc && !npc.isPlayer()) {
IInventory merchant = ((ContainerMerchant)this.entity.openContainer).getMerchantInventory();
this.sendPacket(new SPacketOpenWindow(this.currentWindowId, npc.getId(), merchant.getSizeInventory()));
MerchantRecipeList trades = npc.getTrades(this.entity);
if(trades != null)
this.sendPacket(new SPacketTrades(trades, this.currentWindowId));
}
}
// public void addStat(int amount)
// {
// this.setStat(stat, this.getStat(stat) + amount);
// }
//
// public void removeStat(StatBase stat)
// {
// if (stat != null)
// {
// this.setStat(stat, 0);
// }
// }
public void onItemUseFinish()
{
this.sendPacket(new SPacketEntityStatus(this.entity, (byte)9));
}
// /**
// * sets the itemInUse when the use item button is clicked. Args: itemstack, int maxItemUseDuration
// */
// public void setItemInUse(ItemStack stack, int duration)
// {
// super.setItemInUse(stack, duration);
//
// if (stack != null && stack.getItem() != null && stack.getItem().getItemUseAction(stack) == ItemAction.EAT)
// {
// this.getServerWorld().sendToAllTrackingAndSelf(this, new SPacketAnimation(this, 3));
// }
// }
public void onNewEffect(StatusEffect id)
{
this.sendPacket(new SPacketEntityEffect(this.entity.getId(), id));
}
public void onChangedEffect(StatusEffect id, boolean added)
{
this.sendPacket(new SPacketEntityEffect(this.entity.getId(), id));
}
public void onFinishedEffect(StatusEffect effect)
{
this.sendPacket(new SPacketRemoveEntityEffect(this.entity.getId(), effect));
}
public void setPositionAndUpdate(double x, double y, double z)
{
this.setPlayerLocation(x, y, z, this.entity.rotYaw, this.entity.rotPitch);
}
public void onCriticalHit(Entity entityHit)
{
this.getEntityWorld().sendToAllTrackingAndSelf(this.entity, new SPacketAnimation(entityHit, 4));
}
public void updateEffectMeta()
{
this.getEntityWorld().updateTrackedPlayer(this.entity);
}
public void playSound(SoundEvent name, float volume)
{
this.getEntityWorld().sendNearExcept(this.entity, this.entity.posX, this.entity.posY, this.entity.posZ, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, new SPacketSoundEffect(name, this.entity.posX, this.entity.posY, this.entity.posZ, volume));
}
public void sendSlot(Container container, int index, ItemStack stack)
{
if (!this.isChangingQuantityOnly)
{
this.sendPacket(new SPacketSetSlot(container.windowId, index, stack));
}
}
public void sendContainer(Container container, List<ItemStack> items)
{
this.sendPacket(new SPacketWindowItems(container.windowId, items));
this.sendPacket(new SPacketSetSlot(-1, -1, this.entity.getMouseItem()));
}
public void sendProperty(Container container, int variable, int value)
{
this.sendPacket(new SPacketWindowProperty(container.windowId, variable, value));
}
public static SPacketChunkData.Extracted getExtractedData(WorldServer world, ChunkServer chunk, boolean biomes, int[] extend)
{
Set<BlockArray> aextendedblockstorage = chunk.getStorage();
SPacketChunkData.Extracted dataset = new SPacketChunkData.Extracted();
List<BlockArray> list = Lists.<BlockArray>newArrayList();
if(extend == null) {
for(BlockArray arr : aextendedblockstorage) {
if(arr != null && (!biomes || arr.hasData()))
list.add(arr);
}
}
else {
for(int cy : extend) {
BlockArray arr = chunk.getArray(cy);
if(arr != null && (!biomes || arr.hasData()))
list.add(arr);
}
}
extend = new int[list.size()];
for(int z = 0; z < extend.length; z++) {
extend[z] = list.get(z).getY() >> 4;
}
dataset.extend = extend;
dataset.data = new byte[SPacketChunkData.getSize(extend.length, biomes)];
int j = 0;
for (BlockArray extendedblockstorage1 : list)
{
char[] achar = extendedblockstorage1.getData();
for (char c0 : achar)
{
dataset.data[j++] = (byte)(c0 & 255);
dataset.data[j++] = (byte)(c0 >> 8 & 255);
}
}
if (biomes)
{
BiomeGenerator gen = world.getBiomeGenerator();
for (int n = 0; n < 256; n++)
{
int x = (chunk.xPos << 4) | (n >> 4);
int z = (chunk.zPos << 4) | (n & 15);
int temp = Float.floatToIntBits(gen == null ? 0.0f : gen.getBiomeAt(new LocalPos(x, 0, z)).temperature);
int off = Float.floatToIntBits(world.getTempNoise(x, z));
dataset.data[j++] = (byte)(temp & 255);
dataset.data[j++] = (byte)(temp >> 8 & 255);
dataset.data[j++] = (byte)(temp >> 16 & 255);
dataset.data[j++] = (byte)(temp >> 24 & 255);
dataset.data[j++] = (byte)(off & 255);
dataset.data[j++] = (byte)(off >> 8 & 255);
dataset.data[j++] = (byte)(off >> 16 & 255);
dataset.data[j++] = (byte)(off >> 24 & 255);
}
}
return dataset;
}
private static int copyTo(byte[] src, byte[] dest, int offset)
{
System.arraycopy(src, 0, dest, offset, src.length);
return offset + src.length;
}
public static SPacketChunkData getPacket(WorldServer world, ChunkServer chunkIn, boolean biomes, int[] extend)
{
return new SPacketChunkData(chunkIn.xPos, chunkIn.zPos, biomes, getExtractedData(world, chunkIn, biomes, extend));
}
private static SPacketMapChunkBulk getPacket(WorldServer world, List<ChunkServer> chunks)
{
int i = chunks.size();
int[] xPositions = new int[i];
int[] zPositions = new int[i];
SPacketChunkData.Extracted[] chunksData = new SPacketChunkData.Extracted[i];
for (int j = 0; j < i; ++j)
{
ChunkServer chunk = chunks.get(j);
SPacketChunkData.Extracted s21packetchunkdata$extracted = getExtractedData(world, chunk, true, null);
xPositions[j] = chunk.xPos;
zPositions[j] = chunk.zPos;
chunksData[j] = s21packetchunkdata$extracted;
}
return new SPacketMapChunkBulk(xPositions, zPositions, chunksData);
}
public void updateEntity()
{
if (this.entity.hurtResistance > 0)
{
--this.entity.hurtResistance;
}
this.entity.openContainer.clearStacks();
this.entity.openContainer.detectAndSendChanges();
if(Vars.itemWeight) {
int weight = this.entity.getInventoryWeight();
int capacity = this.entity.getInventoryCapacity();
if(weight > capacity)
this.entity.addEffect(new StatusEffect(Effect.SLOWNESS, 100, Math.min(5, (int)((float)(weight - capacity) / (float)capacity * 10.0f))));
}
// if(!this.worldObj.client)
if (/* !this.worldObj.client && */ !this.entity.openContainer.canInteractWith(this.entity))
{
this.show(null);
}
while (!this.destroyedItemsNetCache.isEmpty())
{
int i = Math.min(this.destroyedItemsNetCache.size(), Integer.MAX_VALUE);
int[] aint = new int[i];
Iterator<Integer> iterator = this.destroyedItemsNetCache.iterator();
int j = 0;
while (iterator.hasNext() && j < i)
{
aint[j++] = ((Integer)iterator.next()).intValue();
iterator.remove();
}
this.sendPacket(new SPacketDestroyEntities(aint));
}
if (!this.loadedChunks.isEmpty())
{
List<ChunkServer> list = Lists.<ChunkServer>newArrayList();
Iterator<ChunkPos> iterator1 = this.loadedChunks.iterator();
List<TileEntity> list1 = Lists.<TileEntity>newArrayList();
WorldServer world = this.getEntityWorld();
int n = SVars.chunksPerTick;
while (iterator1.hasNext() && ((List)list).size() < n)
{
ChunkPos chunkcoordintpair = (ChunkPos)iterator1.next();
if (chunkcoordintpair != null)
{
if (world.isBlockLoaded(new LocalPos(chunkcoordintpair.x << 4, 0, chunkcoordintpair.z << 4)))
{
ChunkServer chunk = world.getChunk(chunkcoordintpair.x, chunkcoordintpair.z);
if (chunk.isTerrainPopulated())
{
list.add(chunk);
list1.addAll(world.getTileEntitiesIn(chunkcoordintpair.x * 16, -World.MAX_SIZE_Y, chunkcoordintpair.z * 16, chunkcoordintpair.x * 16 + 16, World.MAX_SIZE_Y, chunkcoordintpair.z * 16 + 16));
iterator1.remove();
}
}
}
else
{
iterator1.remove();
}
}
if (!list.isEmpty())
{
if (list.size() == 1)
{
this.sendPacket(getPacket(world, list.get(0), true, null));
}
else
{
if(list.size() <= 10) {
this.sendPacket(getPacket(world, list));
}
else {
for(int h = 0; h < list.size(); h += 10) {
this.sendPacket(getPacket(world, list.subList(h, h + 10 > list.size() ? list.size() : h + 10)));
}
}
}
for (TileEntity tileentity : list1)
{
this.sendTileEntityUpdate(tileentity);
}
for (ChunkServer chunk1 : list)
{
this.getEntityWorld().updateChunksForPlayer(this.entity, chunk1);
}
}
}
++this.curblockDamage;
if (this.receivedFinishDiggingPacket)
{
int i = this.curblockDamage - this.initialBlockDamage;
Block block = this.entity.worldObj.getState(this.removingPos).getBlock();
if (block == Blocks.air)
{
this.receivedFinishDiggingPacket = false;
}
else
{
float f = block.getHardness(this.entity, this.entity.worldObj, this.removingPos) * (float)(i + 1);
int j = (int)(f * 10.0F);
if (j != this.durabilityRemainingOnBlock)
{
this.durabilityRemainingOnBlock = j;
}
if (f >= 1.0F)
{
this.receivedFinishDiggingPacket = false;
this.tryHarvestBlock(this.removingPos);
}
}
}
else if (this.isDestroyingBlock)
{
Block block1 = this.entity.worldObj.getState(this.startPos).getBlock();
if (block1 == Blocks.air)
{
this.durabilityRemainingOnBlock = -1;
this.isDestroyingBlock = false;
}
else
{
int k = this.curblockDamage - this.initialDamage;
float f1 = block1.getHardness(this.entity, this.entity.worldObj, this.removingPos) * (float)(k + 1);
int l = (int)(f1 * 10.0F);
if (l != this.durabilityRemainingOnBlock)
{
this.durabilityRemainingOnBlock = l;
}
}
}
}
public void onBlockClicked(LocalPos pos, Facing side)
{
if(this.onPlayerInteract(true, pos)) {
this.sendPacket(new SPacketBlockChange(this.entity.worldObj, pos));
if(this.entity.getHeldItem() != null && this.entity.getHeldItem().isEmpty())
this.entity.clearHeldItem();
this.entity.openContainer.detectAndSendChanges();
return;
}
// if (this.creative)
// {
// if (!this.worldObj.extinguishFire(null, pos, side))
// {
// this.tryHarvestBlock(pos);
// }
// }
// else
// {
Block block = this.entity.worldObj.getState(pos).getBlock();
this.entity.worldObj.extinguishFire(null, pos, side);
this.initialDamage = this.curblockDamage;
float f = 1.0F;
if (block != Blocks.air)
{
block.onStartBreak(this.entity.worldObj, pos, this.entity);
f = block.getHardness(this.entity, this.entity.worldObj, pos);
}
if (block != Blocks.air && f >= 1.0F)
{
this.tryHarvestBlock(pos);
}
else
{
this.isDestroyingBlock = true;
this.startPos = pos;
int i = (int)(f * 10.0F);
this.durabilityRemainingOnBlock = i;
}
// }
}
public void blockRemoving(LocalPos pos)
{
if (pos.equals(this.startPos))
{
int i = this.curblockDamage - this.initialDamage;
Block block = this.entity.worldObj.getState(pos).getBlock();
if (block != Blocks.air)
{
float f = block.getHardness(this.entity, this.entity.worldObj, pos) * (float)(i + 1);
if (f >= 0.7F)
{
this.isDestroyingBlock = false;
this.tryHarvestBlock(pos);
}
else if (!this.receivedFinishDiggingPacket)
{
this.isDestroyingBlock = false;
this.receivedFinishDiggingPacket = true;
this.removingPos = pos;
this.initialBlockDamage = this.initialDamage;
}
}
}
}
public void cancelDestroyingBlock()
{
this.isDestroyingBlock = false;
}
private boolean removeBlock(LocalPos pos)
{
State iblockstate = this.entity.worldObj.getState(pos);
iblockstate.getBlock().preBroken(this.entity.worldObj, pos, iblockstate, this.entity);
boolean flag = this.entity.worldObj.setBlockToAir(pos);
if (flag)
{
iblockstate.getBlock().onBroken(this.entity.worldObj, pos, iblockstate);
}
return flag;
}
private boolean tryHarvestBlock(LocalPos pos)
{
// if (this.getHeldItem() != null && !this.getHeldItem().getItem().canBreakBlocks())
// {
// return false;
// }
// else
// {
State iblockstate = this.entity.worldObj.getState(pos);
TileEntity tileentity = this.entity.worldObj.getTileEntity(pos);
this.entity.worldObj.playEffect(this.entity, 2001, pos, BlockRegistry.getId(iblockstate));
boolean flag1 = this.removeBlock(pos);
// if (this.creative)
// {
// this.netHandler.sendPacket(new SPacketBlockChange(this.worldObj, pos));
// }
// else
// {
ItemStack itemstack1 = this.entity.getHeldItem();
boolean flag = this.entity.canHarvestBlock(iblockstate.getBlock());
if (itemstack1 != null)
{
itemstack1.getItem().onBlockDestroyed(itemstack1, this.entity.worldObj, iblockstate.getBlock(), pos, this.entity);
if (itemstack1.isEmpty())
{
this.entity.clearHeldItem();
}
}
if (flag1 && flag)
{
iblockstate.getBlock().postBroken(this.entity.worldObj, this.entity, pos, iblockstate, tileentity);
}
// }
return flag1;
// }
}
public void tryUseItem(ItemStack stack)
{
if(this.itemUseCooldown > 0)
return;
int i = stack.getSize();
int j = stack.getItemDamage();
this.itemUseCooldown = stack.getItem().getUseCooldown(stack, this.entity.worldObj, this.entity);
ItemStack itemstack = stack.getItem().onItemRightClick(stack, this.entity.worldObj, this.entity);
if (itemstack != stack || itemstack != null && (itemstack.getSize() != i || itemstack.getMaxItemUseDuration() > 0 || itemstack.getItemDamage() != j))
{
this.entity.setHeldItem(itemstack);
if (itemstack.isEmpty())
{
this.entity.clearHeldItem();
}
if (!this.entity.isUsingItem())
{
this.sendContainer(this.entity.inventoryContainer, this.entity.inventoryContainer.getInventory());
}
}
}
public boolean activateBlockOrUseItem(ItemStack stack, LocalPos pos, Facing side, float offsetX, float offsetY, float offsetZ)
{
if(this.onPlayerInteract(false, pos)) {
this.sendPacket(new SPacketBlockChange(this.entity.worldObj, pos));
stack.getItem().onItemUse(stack, this.entity, this.entity.worldObj, pos, side, offsetX, offsetY, offsetZ);
if(stack.isEmpty())
this.entity.clearHeldItem();
this.entity.openContainer.detectAndSendChanges();
return false;
}
if (!this.entity.isSneaking() || this.entity.getHeldItem() == null) // && (stack == null || !stack.getItem().ignoresBlocks()))
{
State iblockstate = this.entity.worldObj.getState(pos);
if (iblockstate.getBlock().onUse(this.entity.worldObj, pos, iblockstate, this.entity, side, offsetX, offsetY, offsetZ))
{
return true;
}
}
if (stack == null)
{
return false;
}
// else if (this.creative)
// {
// int j = stack.getMetadata();
// int i = stack.stackSize;
// boolean flag = stack.onItemUse(this, this.worldObj, pos, side, offsetX, offsetY, offsetZ);
// stack.setItemDamage(j);
// stack.stackSize = i;
// return flag;
// }
else
{
return stack.getItem().onItemUse(stack, this.entity, this.entity.worldObj, pos, side, offsetX, offsetY, offsetZ);
}
}
public void setSelection(boolean primary, LocalPos pos) {
switch(this.edit) {
case SELECT:
if(primary)
this.selectPos1(pos);
else
this.selectPos2(pos);
break;
case COPYPASTE:
if(primary)
this.pasteClipboard();
else
this.copyClipboard();
break;
case TRANSFORM:
if(primary)
this.rotateClipboard();
else
this.flipClipboard();
}
}
private boolean onPlayerInteract(boolean primary, LocalPos pos) {
if(this.entity.getHeldItem() != null && this.entity.getHeldItem().getItem().onAction(this.entity.getHeldItem(), this.entity, this.entity.worldObj, primary ? ItemControl.PRIMARY : ItemControl.SECONDARY, pos))
return true;
return false;
}
private void selectPos1(LocalPos pos) {
LocalPos point = pos == null ? this.entity.getPosition() : pos;
String msg = this.selectPoint(point, false);
if(msg != null)
this.addHotbar(Color.DARK_RED + msg);
}
private void selectPos2(LocalPos pos) {
LocalPos point = pos == null ? this.entity.getPosition() : pos;
String msg = this.selectPoint(point, true);
if(msg != null)
this.addHotbar(Color.MIDNIGHT + msg);
}
private String selectPoint(LocalPos position, boolean second) {
if(this.selectionDim == Integer.MIN_VALUE || this.selectionDim != UniverseRegistry.getId(this.entity.worldObj.dimension)) {
this.selectionDim = UniverseRegistry.getId(this.entity.worldObj.dimension);
this.selPos1 = null;
this.selPos2 = null;
}
// this.setSelectionWorld();
LocalPos current = second ? this.selPos2 : this.selPos1;
if(current != null && (position.compareTo(current) == 0))
return null;
if(second)
this.selPos2 = current = position;
else
this.selPos1 = current = position;
if(this.selPos1 != null && this.selPos2 != null)
return (second ? "Zweite" : "Erste") + " Position auf " + current + " gesetzt (" + this.getSelectionArea() + ")";
else
return (second ? "Zweite" : "Erste") + " Position auf " + current + " gesetzt";
}
public void setSelectMode() {
String msg = (this.edit = EditAction.values()[(this.edit.ordinal() + 1) % EditAction.values().length]).display;
if(this.edit == EditAction.COPYPASTE && this.clipboard != null) {
int nx = this.clipboard.length;
int ny = this.clipboard[0].length;
int nz = this.clipboard[0][0].length;
msg += String.format("; Zwischenablage: %dx%dx%d (%d)", nx, ny, nz, nx * ny * nz);
}
if(this.edit == EditAction.SELECT && this.selectionDim != Integer.MIN_VALUE && (this.selPos1 != null || this.selPos2 != null)) {
Dimension dim = UniverseRegistry.getDimension(this.selectionDim);
if(dim != null) {
msg += "; Bereich " + dim.getDisplay() + ": ";
msg += (this.selPos1 != null ? this.selPos1 : "*") + " -> " + (this.selPos2 != null ? this.selPos2 : "*");
if(this.selPos1 != null && this.selPos2 != null) {
msg += " = " + (1 + Math.max(this.selPos1.getX(), this.selPos2.getX()) - Math.min(this.selPos1.getX(), this.selPos2.getX())) +
"x" + (1 + Math.max(this.selPos1.getY(), this.selPos2.getY()) - Math.min(this.selPos1.getY(), this.selPos2.getY())) +
"x" + (1 + Math.max(this.selPos1.getZ(), this.selPos2.getZ()) - Math.min(this.selPos1.getZ(), this.selPos2.getZ())) + " (" + this.getSelectionArea() + ")";
}
}
}
if(this.edit == EditAction.TRANSFORM && (this.rotation != 0 || this.flipX || this.flipZ))
msg += "; " + this.getRotationInfo();
this.addHotbar(Color.YELLOW + msg);
}
private int getSelectionArea() {
if(this.selPos1 == null || this.selPos2 == null)
return 0;
return (1 + Math.max(this.selPos1.getX(), this.selPos2.getX()) - Math.min(this.selPos1.getX(), this.selPos2.getX())) *
(1 + Math.max(this.selPos1.getY(), this.selPos2.getY()) - Math.min(this.selPos1.getY(), this.selPos2.getY())) *
(1 + Math.max(this.selPos1.getZ(), this.selPos2.getZ()) - Math.min(this.selPos1.getZ(), this.selPos2.getZ()));
}
private boolean pasteClipboard() {
if(this.clipboard == null)
return false;
int nx = this.clipboard.length;
int ny = this.clipboard[0].length;
int nz = this.clipboard[0][0].length;
LocalPos to = this.entity.getPosition();
ClipboardPlacer placer = new ClipboardPlacer(this.getEntityWorld());
Mat2i transform = null;
if(this.rotation != 0 || this.flipX || this.flipZ) {
transform = new Mat2i(this.rotation, this.flipX, this.flipZ);
}
else {
to = to.add(this.selOffset);
}
for(int x = 0; x < nx; x++) {
for(int y = 0; y < ny; y++) {
for(int z = 0; z < nz; z++) {
if(transform == null) {
placer.setBlock(to.add(x, y, z), this.clipboard[x][y][z]);
}
else {
ClipboardBlock block = transformBlock(transform, this.clipboard[x][y][z]);
placer.setBlock(to.add(transform.mulX(x + this.selOffset.getX(), z + this.selOffset.getZ()), y + this.selOffset.getY(),
transform.mulZ(x + this.selOffset.getX(), z + this.selOffset.getZ())), block);
}
}
}
}
if(transform != null) {
to = to.add(transform.mulX(this.selOffset.getX(), this.selOffset.getZ()), this.selOffset.getY(), transform.mulZ(this.selOffset.getX(), this.selOffset.getZ()));
}
placer.commit();
this.addHotbar(Color.YELLOW + "Zwischenablage wurde bei %d, %d, %d eingefügt", to.getX(), to.getY(), to.getZ());
return true;
}
private static ClipboardBlock transformBlock(Mat2i transform, ClipboardBlock block) {
RotationValue[] state = RotationRegistry.getRotation(block.getState().getBlock());
if(state == null)
return block;
for(RotationValue value : state) {
if(value.isSet(block.getState())) {
RotationValue newValue = getNewRotation(transform, state, value);
if(newValue != null)
block.setState(newValue.set(block.getState()));
break;
}
}
return block;
}
private static double dot(double x1, double z1, double x2, double z2) {
double l1 = Math.sqrt(x1 * x1 + z1 * z1);
double l2 = Math.sqrt(x2 * x2 + z2 * z2);
return (x1 / l1) * (x2 / l2) + (z1 / l1) * (z2 / l2);
}
private static RotationValue getNewRotation(Mat2i transform, RotationValue[] state, RotationValue value) {
int x = transform.mulX(value.getX(), value.getZ());
int z = transform.mulZ(value.getX(), value.getZ());
RotationValue newValue = null;
double closest = -2;
for(RotationValue v : state) {
if(v.canTransform(value)) {
double dot = dot(v.getX(), v.getZ(), x, z);
if(dot >= closest) {
closest = dot;
newValue = v;
}
}
}
return newValue;
}
public Iterable<MutablePos> getSelectedBlocks() {
if(this.selectionDim == Integer.MIN_VALUE || this.selectionDim != UniverseRegistry.getId(this.entity.worldObj.dimension) ||
this.selPos1 == null || this.selPos2 == null)
return null;
return MutablePos.mutableArea(this.selPos1, this.selPos2);
}
private boolean copyClipboard() {
if(this.selectionDim == Integer.MIN_VALUE || this.selectionDim != UniverseRegistry.getId(this.entity.worldObj.dimension) ||
this.selPos1 == null || this.selPos2 == null)
return false;
WorldServer source = this.getEntityWorld();
int mx = Math.min(this.selPos1.getX(), this.selPos2.getX());
int my = Math.min(this.selPos1.getY(), this.selPos2.getY());
int mz = Math.min(this.selPos1.getZ(), this.selPos2.getZ());
int nx = Math.max(this.selPos1.getX(), this.selPos2.getX());
int ny = Math.max(this.selPos1.getY(), this.selPos2.getY());
int nz = Math.max(this.selPos1.getZ(), this.selPos2.getZ());
this.clipboard = new ClipboardBlock[1 + nx - mx][1 + ny - my][1 + nz - mz];
for(int x = mx; x <= nx; x++) {
for(int y = my; y <= ny; y++) {
for(int z = mz; z <= nz; z++) {
this.clipboard[x - mx][y - my][z - mz] = source.getBlock(new LocalPos(x, y, z));
}
}
}
this.rotation = 0;
this.flipX = this.flipZ = false;
LocalPos pos = this.entity.getPosition();
this.selOffset = new Vec3i(mx - pos.getX(), my - pos.getY(), mz - pos.getZ());
this.addHotbar(Color.YELLOW + "Auswahl wurde in die Zwischenablage kopiert");
return true;
}
private String getRotationInfo() {
return (this.rotation == 0 ? "" : ("Rotation " + this.rotation + "°")) +
(this.rotation == 0 || (!this.flipX && !this.flipZ) ? "" : ", ") +
(this.flipX && this.flipZ ? "X und Z gedreht" : (this.flipX ? "X gedreht" : (this.flipZ ? "Z gedreht" : "")));
}
private void flipClipboard() {
if(this.clipboard == null || this.entity.rotPitch > 67.5f || this.entity.rotPitch < -67.5f)
return;
float rot = this.entity.rotYaw % 360.0f;
if(rot < 0.0f)
rot += 360.0f;
if (0.0f <= rot && rot < 22.5f)
this.flipZ ^= true;
else if (67.5f <= rot && rot < 112.5)
this.flipX ^= true;
else if (157.5f <= rot && rot < 202.5f)
this.flipZ ^= true;
else if (247.5f <= rot && rot < 292.5f)
this.flipX ^= true;
else if (337.5f <= rot && rot < 360.0f)
this.flipZ ^= true;
else
return;
String info = this.getRotationInfo();
this.addHotbar(Color.YELLOW + (info.isEmpty() ? "Keine Drehung" : info));
}
private void rotateClipboard() {
if(this.clipboard == null)
return;
this.rotation = (this.rotation + 90) % 360;
String info = this.getRotationInfo();
this.addHotbar(Color.YELLOW + (info.isEmpty() ? "Keine Drehung" : info));
}
public TagObject readCharacter() {
return this.characters.isEmpty() || this.selected < 0 ? null : this.characters.get(this.selected);
}
public void writeCharacter(TagObject tag) {
if(!this.characters.isEmpty() && this.selected >= 0)
this.characters.set(this.selected, tag);
}
public void disconnect(String message)
{
Log.NETWORK.info("Trenne %s: %s", this.getUser(), message);
this.connection.sendPacket(new SPacketDisconnect(message), new GenericFutureListener < Future <? super Void >> ()
{
public void operationComplete(Future <? super Void > p_operationComplete_1_) throws Exception
{
Player.this.connection.closeChannel("Getrennt");
}
});
this.connection.disableAutoRead();
this.server.schedule(new Runnable()
{
public void run()
{
Player.this.connection.checkDisconnected();
}
});
}
public void onDisconnect(String reason)
{
Log.NETWORK.info(this.getUser() + " wurde getrennt: " + Color.stripCodes(reason));
this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel verlassen", this.getUser()), Type.FEED));
this.server.removePlayer(this);
}
public PlayerCharacter getCharacterInfo(TagObject tag) {
String name = tag.getString("CustomName");
String info = tag.getString("Description");
if(info != null && info.isEmpty())
info = null;
Alignment align = Alignment.getByName(tag.getString("Align"));
Dimension dimension = UniverseRegistry.getDimension(tag.getString("Dimension"));
String dim = dimension == null ? "???" : dimension.getDisplay();
LocalPos pos = new LocalPos(tag.getDouble("PosX"), tag.getDouble("PosY"), tag.getDouble("PosZ"));
String type = EntityRegistry.getEntityName(tag.getString("id"));
int level = tag.getInt("XpLevel");
Dimension origin = UniverseRegistry.getDimension(tag.getString("OriginDim"));
return new PlayerCharacter(name, info, align, dim, pos, type, level, origin == null || origin == Space.INSTANCE ? null : origin.getDisplay());
}
public void onConnect() {
List<PlayerCharacter> chars = Lists.newArrayList();
for(TagObject tag : this.characters) {
chars.add(this.getCharacterInfo(tag));
}
this.sendPacket(new SPacketCharacterList(this.selected, chars));
this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel betreten", this.getUser()), Type.FEED));
}
public void sendPacket(final Packet packet)
{
this.connection.sendPacket(packet);
}
public void setPlayerLocation(double x, double y, double z, float yaw, float pitch)
{
this.setPlayerLocation(x, y, z, yaw, pitch, Collections.<SPacketPlayerPosLook.EnumFlags>emptySet());
}
public void setPlayerLocation(double x, double y, double z, float yaw, float pitch, Set<SPacketPlayerPosLook.EnumFlags> flags)
{
this.hasMoved = false;
this.lastPosX = x;
this.lastPosY = y;
this.lastPosZ = z;
if (flags.contains(SPacketPlayerPosLook.EnumFlags.X))
{
this.lastPosX += this.entity.posX;
double nx = ExtMath.clampd(this.lastPosX, -World.MAX_SIZE + 1, World.MAX_SIZE - 1);
if(nx != this.lastPosX) {
x = (x < 0.0 ? (double)(-World.MAX_SIZE + 1) : (double)(World.MAX_SIZE - 1)) - this.entity.posX;
this.lastPosX = x + this.entity.posX;
}
}
if (flags.contains(SPacketPlayerPosLook.EnumFlags.Y))
{
this.lastPosY += this.entity.posY;
}
if (flags.contains(SPacketPlayerPosLook.EnumFlags.Z))
{
this.lastPosZ += this.entity.posZ;
double nz = ExtMath.clampd(this.lastPosZ, -World.MAX_SIZE + 1, World.MAX_SIZE - 1);
if(nz != this.lastPosZ) {
z = (z < 0.0 ? (double)(-World.MAX_SIZE + 1) : (double)(World.MAX_SIZE - 1)) - this.entity.posZ;
this.lastPosZ = z + this.entity.posZ;
}
}
float nyaw = yaw;
float npitch = pitch;
if (flags.contains(SPacketPlayerPosLook.EnumFlags.Y_ROT))
{
nyaw = yaw + this.entity.rotYaw;
}
if (flags.contains(SPacketPlayerPosLook.EnumFlags.X_ROT))
{
npitch = pitch + this.entity.rotPitch;
}
this.entity.setPositionAndRotation(this.lastPosX, this.lastPosY, this.lastPosZ, nyaw, npitch);
this.entity.connection.sendPacket(new SPacketPlayerPosLook(x, y, z, yaw, pitch, flags));
}
public void processKeepAlive(CPacketKeepAlive packetIn)
{
if (packetIn.getValue() == this.pingKey)
{
int i = (int)((System.nanoTime() / 1000000L) - this.lastPingTime);
this.ping = (this.ping * 3 + i) / 4;
this.ping = Math.max(this.ping, 0);
}
}
// private boolean runScript(String line) {
// if(!this.isAdmin() || !line.startsWith("+") || line.length() < 2)
// return false;
// line = line.substring(1).trim();
// PythonInterpreter py = new PythonInterpreter();
// py.set("handler", this);
// py.set("entity", this.entity);
// py.set("server", this.server);
// py.set("user", this.user);
// py.execfile(NetHandlerPlayServer.class.getResourceAsStream("/scripts/" + line + ".py"), line + ".py");
// py.close();
// return true;
// }
private boolean sendPlayer(String line) {
if(!line.startsWith("@") || line.length() < 2)
return false;
int space = line.indexOf(' ');
// if(space < 0)
// return false;
Player target = this.server.getPlayer(space < 0 ? line.substring(1) : line.substring(1, space));
if(target == null)
return false;
target.addChat(this.entity.getEnclosedName(Color.LIGHT_GRAY) + " -> " + target.entity.getEnclosedName(Color.LIGHT_GRAY) + " " +
line);
if(target != this)
this.addChat(target.entity.getEnclosedName(Color.LIGHT_GRAY) + " -> " + this.entity.getEnclosedName(Color.LIGHT_GRAY) + " " +
line);
return true;
}
private boolean sendEmote(String line) {
if(!line.startsWith("*") || line.length() < 2)
return false;
String str = line.substring(1).trim();
if(str.isEmpty())
return false;
this.server.sendPacket(new SPacketMessage(String.format(Color.LIGHT_GRAY + "* %s %s", this.entity.getEnclosedName(Color.LIGHT_GRAY), str), Type.CHAT));
return true;
}
public void setAdmin(boolean admin) {
super.setAdmin(admin);
if(!this.isAdmin() && this.entity != null && this.entity.noclip) {
this.entity.noclip = false;
this.entity.flying &= this.entity.hasEffect(Effect.FLYING) || this.entity.canNaturallyFly();
this.entity.fallDistance = 0.0F;
this.sendPlayerAbilities();
this.addFeed(Color.RED + "NoClip wurde deaktiviert");
}
}
// private Long parseInt(String input, long max) {
// long num;
// try {
// num = Long.parseLong(input);
// }
// catch(NumberFormatException e) {
// this.addFeed(TextColor.DRED + "'%s' ist keine gültige Zahl", input);
// return null;
// }
//
// if(num < 0) {
// this.addFeed(TextColor.DRED + "Die Zeit muss mindestens 0 betragen", num);
// return null;
// }
// else if(num > max) {
// this.addFeed(TextColor.DRED + "Die Zeit darf höchstens %d betragen", num, max);
// return null;
// }
// else {
// return num;
// }
// }
// private Double parseCoordinate(String str, boolean center) {
// try {
// return (double)Integer.parseInt(str) + (center ? 0.5 : 0.0);
// }
// catch(NumberFormatException e) {
// this.addFeed(TextColor.DRED + "'%s' ist keine gültige Zahl", str);
// return null;
// }
// }
// private boolean teleport(String line) {
// if(!Config.teleportAllowed && !this.isAdmin())
// return false;
// line = line.trim();
// String[] argv = line.split(" ", -1);
// if(line.isEmpty() || argv.length == 0 || argv.length == 2) {
// this.addFeed(TextColor.DRED + "+Spieler, @Warp, *Dimension oder X Y Z [Dimension]");
// return true;
// }
// String tgt = argv[0];
// if(tgt.equals("#")) {
// if(argv.length < 4) {
// this.addFeed(TextColor.DRED + "# X Y Z [Dimension]");
// return true;
// }
// Double ax = parseCoordinate(argv[1], true);
// if(ax == null)
// return true;
// Double ay = parseCoordinate(argv[2], false);
// if(ay == null)
// return true;
// Double az = parseCoordinate(argv[3], true);
// if(az == null)
// return true;
// int dimension = this.entity.worldObj.dimension.getDimensionId();
// if(argv.length > 4) {
// WorldServer world;
// try {
// world = this.server.getWorld(Integer.parseInt(argv[4]));
// }
// catch(NumberFormatException e) {
// world = this.server.getWorld(argv[4]);
// }
// if(world == null) {
// this.addFeed(TextColor.DRED + "Dimension '%s' existiert nicht", argv[4]);
// return true;
// }
// dimension = world.dimension.getDimensionId();
// }
// this.entity.teleport(ax, ay, az, this.entity.rotYaw, this.entity.rotPitch, dimension);
// }
// if(tgt.startsWith("@")) {
// tgt = tgt.substring(1);
// if(tgt.equals("spawn")) {
// WorldServer world = this.server.getWorld(Config.spawnDim);
// world = world == null ? this.server.getSpace() : world;
// int y = Config.spawnY;
// while(world.getState(new BlockPos(Config.spawnX, y, Config.spawnZ)).getBlock().getMaterial().blocksMovement() && y < 511)
// y++;
// this.entity.teleport(Config.spawnX + 0.5d, (double)y, Config.spawnZ + 0.5d,
// Config.spawnYaw, Config.spawnPitch, world.dimension.getDimensionId());
// }
// else {
// Position pos = this.server.getWarps().get(tgt);
// if(pos == null) {
// this.addFeed(TextColor.DRED + "Warp '%s' existiert nicht", tgt);
// return true;
// }
// if(this.server.getWorld(pos.dim) == null) {
// this.addFeed(TextColor.DRED + "Warp '%s' hat kein Level (%s)", tgt, pos.dim);
// return true;
// }
// this.entity.teleport(pos);
// }
// return true;
// }
// else if(tgt.startsWith("*")) {
// tgt = tgt.substring(1);
// WorldServer world;
// try {
// world = this.server.getWorld(Integer.parseInt(tgt));
// }
// catch(NumberFormatException e) {
// world = this.server.getWorld(tgt);
// }
// if(world == null) {
// this.addFeed(TextColor.DRED + "Dimension '%s' existiert nicht", tgt);
// return true;
// }
//// int dimension = world.dimension.getDimensionId();
//// int dimension = parseDimension(sender, tgt);
// BlockPos pos = this.entity.getPosition();
//// WorldServer world = Server.getServer().getWorld(dimension);
// pos = pos.getY() < 0 ? new BlockPos(pos.getX(), 0, pos.getZ()) : pos;
// if(world.getState(pos).getBlock().getMaterial().blocksMovement() || world.getState(pos).getBlock().getMaterial().isLiquid()) {
// while((world.getState(pos).getBlock().getMaterial().blocksMovement() || world.getState(pos).getBlock().getMaterial().isLiquid()) && pos.getY() < 511)
// pos = pos.up();
// }
// else {
// while(!(world.getState(pos).getBlock().getMaterial().blocksMovement() || world.getState(pos).getBlock().getMaterial().isLiquid()) && pos.getY() > 0)
// pos = pos.down();
// pos = pos.up();
// }
// this.entity.teleport(pos, world.dimension.getDimensionId());
// return true;
// }
// else if(tgt.startsWith("+")) {
// tgt = tgt.substring(1);
// NetHandlerPlayServer conn = this.server.getPlayer(tgt);
// if(conn == null) {
// Position pos = this.server.getOfflinePosition(tgt);
// if(pos == null) {
// this.addFeed(TextColor.DRED + "Spieler '%s' konnte nicht gefunden werden", tgt);
// return true;
// }
// this.entity.teleport(pos);
// }
// else {
// EntityNPC dest = conn.getEntity();
// if(dest != null)
// this.entity.teleport(dest.posX, dest.posY, dest.posZ, dest.rotYaw, dest.rotPitch, dest.worldObj.dimension.getDimensionId());
// }
// return true;
// }
// return false;
// }
private void runCommand(String command) {
if(this.isAdmin())
this.server.getScriptEnvironment().execute(command, this);
else
this.addConsole(Color.DARK_RED + "Nur Admins können Befehle ausführen");
}
private List<String> completeCommand(String command) {
return this.server.getScriptEnvironment().complete(command, this);
// return Lists.newArrayList();
}
public void setForcedExec(Executor forced) {
this.forcedExec = forced;
}
public void setExecPos(Position pos) {
this.forcedPos = pos;
}
public void log(String msg) {
if(this.forcedExec != null)
this.forcedExec.log(Color.ACID + "Als " + Color.GREEN + "%s" + Color.DARK_GRAY + ": " + Color.RESET + "%s", this.getUser(), msg);
else
this.addConsole(msg);
}
public Position getExecPos() {
return this.forcedPos != null ? this.forcedPos : (this.entity != null ? this.entity.getPos() : null);
}
public Entity getPointedEntity() {
return this.pointedEntity != -1 && this.entity != null ? this.entity.worldObj.getEntityByID(this.pointedEntity) : null;
}
public LocalPos getPointedPosition() {
return this.pointedPosition;
}
public boolean isPlayer() {
return true;
}
public void processMessage(CPacketMessage packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
String msg = packetIn.getMessage();
for(int z = 0; z < msg.length(); z++) {
char c = msg.charAt(z);
if(c < 32 || c == 127)
throw new IllegalArgumentException("Ungültige Zeichen in Nachricht");
}
CPacketMessage.Type type = packetIn.getType();
if(this.charEditor != (type == CPacketMessage.Type.DISPLAY || type == CPacketMessage.Type.INFO))
return;
switch(type) {
case COMMAND:
this.runCommand(msg); // this.addFeed(TextColor.RED + "Befehl wurde nicht gefunden");
break;
case CHAT:
if(!this.sendPlayer(msg) && !this.sendEmote(msg))
this.server.sendPacket(new SPacketMessage(String.format("%s %s", this.entity.getEnclosedName(Color.LIGHT_GRAY), msg), Type.CHAT));
break;
case DISPLAY:
if(msg.isEmpty() || !IPlayer.isValidNick(msg) || msg.length() > IPlayer.MAX_NICK_LENGTH)
throw new IllegalArgumentException("Ungültiger Anzeigename");
this.entity.setCustomNameTag(msg);
break;
case INFO:
if(msg.length() > IPlayer.MAX_INFO_LENGTH)
throw new IllegalArgumentException("Ungültige Beschreibung");
this.entity.setDescription(msg.isEmpty() ? null : msg);
break;
case ITEM:
if(msg.length() > 30)
throw new IllegalArgumentException("Ungültiger Name");
if(packetIn.getArg() == -1) {
if(this.entity.getSelectedIndex() >= 0)
this.entity.inventoryContainer.renameItem(Equipment.ARMOR_SLOTS + this.entity.getSelectedIndex(), msg);
}
else {
this.entity.openContainer.renameItem(packetIn.getArg(), msg);
}
this.entity.openContainer.detectAndSendChanges();
break;
default:
throw new IllegalArgumentException("Ungültiger Nachrichten-Typ!");
}
}
public void processComplete(CPacketComplete packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
if(this.charEditor || !this.isAdmin()) {
this.entity.connection.sendPacket(new SPacketTabComplete(new String[0]));
return;
}
this.pointedEntity = packetIn.getEntityId();
this.pointedPosition = packetIn.getPosition();
if(packetIn.getMessage().startsWith(" ")) {
this.entity.connection.sendPacket(new SPacketTabComplete(new String[0]));
return;
}
List<String> list = this.completeCommand(packetIn.getMessage());
this.entity.connection.sendPacket(new SPacketTabComplete(list.toArray(new String[list.size()])));
}
private static boolean isFinite(double value) {
return Double.NEGATIVE_INFINITY < value & value < Double.POSITIVE_INFINITY;
}
private static boolean isFinite(float value) {
return Float.NEGATIVE_INFINITY < value & value < Float.POSITIVE_INFINITY;
}
public void processPlayer(CPacketPlayer packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
if(this.charEditor)
return;
if (!isFinite(packetIn.getPositionX()) || !isFinite(packetIn.getPositionY()) || !isFinite(packetIn.getPositionZ()) || !isFinite(packetIn.getPitch()) || !isFinite(packetIn.getYaw()))
{
throw new IllegalArgumentException("Ungültige Bewegung");
}
else
{
WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension);
// this.updated = true;
if(packetIn.isCamera()) {
if(this.camera != null) {
this.camera.setPositionClamped(packetIn.getPositionX(), packetIn.getPositionY(), packetIn.getPositionZ());
this.camera.setRotationClamped(packetIn.getYaw(), packetIn.getPitch());
if(!this.camera.fixed && packetIn.isOnGround()) {
this.unsetCamera();
}
else {
this.setPlayerLocation(this.camera.posX, this.camera.posY, this.camera.posZ, this.camera.rotYaw, this.camera.rotPitch);
this.entity.setRotationYawHead(this.camera.rotYaw);
this.getEntityWorld().updateMountedMovingPlayer(this.entity);
}
}
return;
}
double d0 = this.entity.posX;
double d1 = this.entity.posY;
double d2 = this.entity.posZ;
double d3 = 0.0D;
double d4 = packetIn.getPositionX() - this.lastPosX;
double d5 = packetIn.getPositionY() - this.lastPosY;
double d6 = packetIn.getPositionZ() - this.lastPosZ;
if (packetIn.isMoving())
{
d3 = d4 * d4 + d5 * d5 + d6 * d6;
if (!this.hasMoved && d3 < 0.25D)
{
this.hasMoved = true;
}
}
if (this.hasMoved)
{
this.lastMoved = this.tickTime;
if (this.entity.vehicle != null)
{
float f4 = this.entity.rotYaw;
float f = this.entity.rotPitch;
this.entity.vehicle.updateRiderPosition();
double d16 = this.entity.posX;
double d17 = this.entity.posY;
double d18 = this.entity.posZ;
if (packetIn.getRotating())
{
f4 = packetIn.getYaw();
f = packetIn.getPitch();
}
this.entity.onGround = packetIn.isOnGround();
this.entity.onUpdateEntity();
this.updateSync();
this.entity.setPositionAndRotation(d16, d17, d18, f4, f);
if (this.entity.vehicle != null)
{
this.entity.vehicle.updateRiderPosition();
}
this.getEntityWorld().updateMountedMovingPlayer(this.entity);
if (this.entity.vehicle != null)
{
if (d3 > 4.0D)
{
Entity entity = this.entity.vehicle;
this.entity.connection.sendPacket(new SPacketEntityTeleport(entity));
this.setPlayerLocation(this.entity.posX, this.entity.posY, this.entity.posZ, this.entity.rotYaw, this.entity.rotPitch);
}
this.entity.vehicle.isAirBorne = true;
}
if (this.hasMoved)
{
this.lastPosX = this.entity.posX;
this.lastPosY = this.entity.posY;
this.lastPosZ = this.entity.posZ;
}
worldserver.updateEntity(this.entity, true);
return;
}
// if (this.playerEntity.isPlayerSleeping())
// {
// this.playerEntity.onUpdateEntity();
// this.playerEntity.setPositionAndRotation(this.lastPosX, this.lastPosY, this.lastPosZ, this.playerEntity.rotYaw, this.playerEntity.rotPitch);
// worldserver.updateEntity(this.playerEntity, true);
// return;
// }
double d7 = this.entity.posY;
this.lastPosX = this.entity.posX;
this.lastPosY = this.entity.posY;
this.lastPosZ = this.entity.posZ;
double d8 = this.entity.posX;
double d9 = this.entity.posY;
double d10 = this.entity.posZ;
float f1 = this.entity.rotYaw;
float f2 = this.entity.rotPitch;
if (packetIn.isMoving() && packetIn.getPositionY() == -99999999.0D)
{
packetIn.setMoving(false);
}
if (packetIn.isMoving())
{
d8 = packetIn.getPositionX();
d9 = packetIn.getPositionY();
d10 = packetIn.getPositionZ();
if (Math.abs(packetIn.getPositionX()) > World.MAX_SIZE || Math.abs(packetIn.getPositionZ()) > World.MAX_SIZE)
{
throw new IllegalArgumentException("Ungültige Position");
// return;
}
}
if (packetIn.getRotating())
{
f1 = packetIn.getYaw();
f2 = packetIn.getPitch();
}
this.entity.onUpdateEntity();
this.updateSync();
this.entity.setPositionAndRotation(this.lastPosX, this.lastPosY, this.lastPosZ, f1, f2);
if (!this.hasMoved)
{
return;
}
double d11 = d8 - this.entity.posX;
double d12 = d9 - this.entity.posY;
double d13 = d10 - this.entity.posZ;
double d14 = this.entity.motionX * this.entity.motionX + this.entity.motionY * this.entity.motionY + this.entity.motionZ * this.entity.motionZ;
double d15 = d11 * d11 + d12 * d12 + d13 * d13;
// if (d15 - d14 > 100.0D && (!this.playerEntity.canUse(Permissions.NOMOVECHECK)))
// {
// Log.warn(this.user + " bewegte sich zu schnell! " + d11 + "," + d12 + "," + d13 + " (" + d11 + ", " + d12 + ", " + d13 + ")");
// this.setPlayerLocation(this.lastPosX, this.lastPosY, this.lastPosZ, this.playerEntity.rotYaw, this.playerEntity.rotPitch);
// return;
// }
float f3 = 0.0625F;
boolean flag = worldserver.getCollidingBoundingBoxes(this.entity, this.entity.getEntityBoundingBox().contract((double)f3, (double)f3, (double)f3)).isEmpty();
if (this.entity.onGround && !packetIn.isOnGround() && d12 > 0.0D)
{
this.entity.jump();
}
this.entity.moveEntity(d11, d12, d13);
this.entity.onGround = packetIn.isOnGround();
d11 = d8 - this.entity.posX;
d12 = d9 - this.entity.posY;
if (d12 > -0.5D || d12 < 0.5D)
{
d12 = 0.0D;
}
d13 = d10 - this.entity.posZ;
d15 = d11 * d11 + d12 * d12 + d13 * d13;
boolean flag1 = false;
if (d15 > 0.0625D) // && /* !this.playerEntity.isPlayerSleeping() && */ !this.playerEntity.creative)
{
flag1 = true;
// Log.warn(this.user + " bewegte sich falsch!");
}
this.entity.setPositionAndRotation(d8, d9, d10, f1, f2);
this.entity.addMovement(this.entity.posX - d0, this.entity.posY - d1, this.entity.posZ - d2);
if (!this.entity.noClip)
{
boolean flag2 = worldserver.getCollidingBoundingBoxes(this.entity, this.entity.getEntityBoundingBox().contract((double)f3, (double)f3, (double)f3)).isEmpty();
if (flag && (flag1 || !flag2)) // && !this.playerEntity.isPlayerSleeping())
{
this.setPlayerLocation(this.lastPosX, this.lastPosY, this.lastPosZ, f1, f2);
return;
}
}
// AxisAlignedBB axisalignedbb = this.playerEntity.getEntityBoundingBox().expand((double)f3, (double)f3, (double)f3).addCoord(0.0D, -0.55D, 0.0D);
// if (!Config.flight && !this.playerEntity.capabilities.allowFlying && worldserver.gravity > 0.0 && !worldserver.checkBlockCollision(axisalignedbb) && !this.netManager.isLocalChannel())
// {
// if (d12 >= -0.03125D)
// {
// ++this.floatingTickCount;
//
// if (this.floatingTickCount > Math.min(80, (int)(80.0 * (2.0 - worldserver.gravity))))
// {
// Log.warn(this.user + " wurde wegen zu langem Aufenthalt in der Luft getrennt!");
// this.kick("Fliegen ist auf diesem Server nicht erlaubt");
// return;
// }
// }
// }
// else
// {
// this.floatingTickCount = 0;
// }
this.entity.onGround = packetIn.isOnGround();
this.getEntityWorld().updateMountedMovingPlayer(this.entity);
this.handleFalling(this.entity.posY - d7, packetIn.isOnGround());
}
else if (this.tickTime - this.lastMoved > 20)
{
this.setPlayerLocation(this.lastPosX, this.lastPosY, this.lastPosZ, this.entity.rotYaw, this.entity.rotPitch);
}
}
}
private void updateSync() {
if (this.entity.getHealth() != this.lastHealth)
{
this.sendPacket(new SPacketUpdateHealth(this.entity.getHealth()));
this.lastHealth = this.entity.getHealth();
}
if (this.entity.getHealth() + this.entity.getAbsorptionAmount() != this.combinedHealth)
{
this.combinedHealth = this.entity.getHealth() + this.entity.getAbsorptionAmount();
}
if (this.entity.experienceTotal != this.lastExperience)
{
this.lastExperience = this.entity.experienceTotal;
this.sendPacket(new SPacketSetExperience(this.entity.experience, this.entity.experienceTotal, this.entity.experienceLevel));
}
}
public void processBreak(CPacketBreak packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
if(this.charEditor || this.entity instanceof EntityCameraHolder)
return;
WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension);
LocalPos blockpos = packetIn.getPosition();
switch (packetIn.getStatus())
{
case DROP_ITEM:
// if (!this.playerEntity.isSpectator())
// {
this.entity.dropOneItem(false);
// }
return;
case DROP_ALL_ITEMS:
// if (!this.playerEntity.isSpectator())
// {
this.entity.dropOneItem(true);
// }
return;
case RELEASE_USE_ITEM:
this.entity.stopUsingItem();
return;
case START_DESTROY_BLOCK:
case ABORT_DESTROY_BLOCK:
case STOP_DESTROY_BLOCK:
double d0 = this.entity.posX - ((double)blockpos.getX() + 0.5D);
double d1 = this.entity.posY - ((double)blockpos.getY() + 0.5D) + 1.5D;
double d2 = this.entity.posZ - ((double)blockpos.getZ() + 0.5D);
double d3 = d0 * d0 + d1 * d1 + d2 * d2;
double max = this.entity.getReachDistance() + 1.0D;
max *= max;
if (d3 > max)
{
return;
}
else if (blockpos.getY() >= World.MAX_SIZE_Y)
{
return;
}
else
{
if (packetIn.getStatus() == CPacketBreak.Action.START_DESTROY_BLOCK)
{
if (World.isValidXZ(blockpos))
{
this.onBlockClicked(blockpos, packetIn.getFacing());
}
else
{
this.sendPacket(new SPacketBlockChange(worldserver, blockpos));
}
}
else
{
if (packetIn.getStatus() == CPacketBreak.Action.STOP_DESTROY_BLOCK)
{
this.blockRemoving(blockpos);
}
else if (packetIn.getStatus() == CPacketBreak.Action.ABORT_DESTROY_BLOCK)
{
this.cancelDestroyingBlock();
}
if (worldserver.getState(blockpos).getBlock() != Blocks.air)
{
this.sendPacket(new SPacketBlockChange(worldserver, blockpos));
}
}
return;
}
default:
throw new IllegalArgumentException("Ungültige Aktion");
}
}
public void processPlace(CPacketPlace packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
if(this.charEditor || this.entity instanceof EntityCameraHolder)
return;
WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension);
ItemStack itemstack = this.entity.getHeldItem();
boolean flag = false;
LocalPos blockpos = packetIn.getPosition();
Facing enumfacing = Facing.getFront(packetIn.getPlacedBlockDirection());
if (packetIn.getPlacedBlockDirection() == 255)
{
if (itemstack == null)
{
return;
}
// if(!InteractionHandler.onPlayerInteract(this.playerEntity, false, null)) {
this.tryUseItem(itemstack);
// }
}
else if (blockpos.getY() < World.MAX_SIZE_Y - 1 || enumfacing != Facing.UP && blockpos.getY() < World.MAX_SIZE_Y)
{
double max = this.entity.getReachDistance() + 3.0D;
max *= max;
if (this.hasMoved && this.entity.getDistanceSq((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D) < max && World.isValidXZ(blockpos))
{
this.activateBlockOrUseItem(itemstack, blockpos, enumfacing, packetIn.getPlacedBlockOffsetX(), packetIn.getPlacedBlockOffsetY(), packetIn.getPlacedBlockOffsetZ());
}
flag = true;
}
else
{
// String comp = String.format("Die maximale Bauhöhe beträgt %d Blöcke", World.HEIGHT);
//// comp.setColor(ChatFormat.RED);
// this.message(comp);
flag = true;
}
if (flag)
{
this.entity.connection.sendPacket(new SPacketBlockChange(worldserver, blockpos));
this.entity.connection.sendPacket(new SPacketBlockChange(worldserver, blockpos.offset(enumfacing)));
}
if(this.entity.getSelectedIndex() < 0)
return;
itemstack = this.entity.getHeldItem();
if (itemstack != null && itemstack.isEmpty())
{
this.entity.clearHeldItem();
itemstack = null;
}
if (itemstack == null || itemstack.getMaxItemUseDuration() == 0)
{
this.isChangingQuantityOnly = true;
this.entity.setHeldItem(ItemStack.copy(this.entity.getHeldItem()));
Slot slot = this.entity.openContainer.getSlotFromInventory(this.entity, this.entity.getSelectedIndex());
this.entity.openContainer.detectAndSendChanges();
this.isChangingQuantityOnly = false;
if (!ItemStack.allEquals(this.entity.getHeldItem(), packetIn.getStack()))
{
this.sendPacket(new SPacketSetSlot(this.entity.openContainer.windowId, slot.slotNumber, this.entity.getHeldItem()));
}
}
}
private void useEntity(int entityId, boolean interact)
{
WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension);
Entity entity = worldserver.getEntityByID(entityId);
if (entity != null)
{
boolean flag = this.entity.canEntityBeSeen(entity);
double max = this.entity.getReachDistance() + 1.0D;
max *= max;
// double d0 = 36.0D;
if(!flag) {
max = (this.entity.getReachDistance() + 1.0D) * 0.5D; // 9.0D
max *= max;
}
if (this.entity.getDistanceSqToEntity(entity) < max)
{
if (interact)
{
this.entity.interactWith(entity);
}
else
{
if (entity instanceof EntityItem || entity instanceof EntityXp || entity instanceof EntityArrow || entity == this.entity)
{
throw new IllegalArgumentException("Ungültiges Objekt angegriffen");
// Log.warn("Spieler " + this.user + " versuchte ein falsches Objekt anzugreifen");
// return;
}
this.entity.attackTargetEntityWithCurrentItem(entity);
}
}
}
}
public void processAction(CPacketAction packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
CPacketAction.Action action = packetIn.getAction();
if((this.charEditor != (action == Action.SET_ALIGN || action == Action.SET_SPECIES || action == Action.SET_CLASS || action == Action.SET_HEIGHT || action == Action.CLOSE_EDITOR || action == Action.CANCEL_EDITOR)) || (this.entity instanceof EntityCameraHolder && action != Action.WARP_MODE && action != Action.PERF && action != Action.START_PROFILING && action != Action.STOP_PROFILING)) // {
// if(this.local && action == Action.CLOSE_EDITOR)
// this.server.setDone();
return;
// }
switch (action)
{
case OPEN_EDITOR: {
this.charEditor = true;
// if(this.local)
// this.server.resetProgress();
TagObject tag = this.server.swapPlayer(this, null, EntityHuman.class);
if(!this.characters.isEmpty() && this.selected >= 0)
this.characters.set(this.selected, tag);
int last = this.selected;
this.selected = -1;
this.teleportPos = this.deathPos = null;
this.sendPacket(!this.characters.isEmpty() && last >= 0 ? new SPacketCharacterList(this.selected, last, this.getCharacterInfo(tag)) : new SPacketCharacterList(this.selected));
break;
}
case CLOSE_EDITOR: {
this.charEditor = false;
this.selected = this.characters.size();
this.characters.add(new TagObject());
WorldServer world = this.server.getWorld(UniverseRegistry.getDimension(packetIn.getAuxData()));
world = world == null ? this.server.getSpace() : world;
GlobalPos origin = new GlobalPos(world.rand.range(-SVars.originRadius, SVars.originRadius), 64, world.rand.range(-SVars.originRadius, SVars.originRadius), world);
this.entity.setOrigin(origin);
Position pos = this.server.getRandomSpawnPosition(origin);
this.entity.teleport(pos);
this.teleportPos = this.deathPos = null;
this.sendPacket(new SPacketCharacterList(this.selected, this.selected, new PlayerCharacter(this.entity.getCustomNameTag(), this.entity.getDescription(), this.entity.getAlignment(), this.entity.worldObj.dimension.getDisplay(), this.entity.getPosition(), EntityRegistry.getEntityName(EntityRegistry.getEntityString(this.entity)), this.entity.experienceLevel, world.dimension == Space.INSTANCE ? null : world.dimension.getDisplay())));
// if(this.local)
// this.server.setDone();
break;
}
case CANCEL_EDITOR: {
int index = packetIn.getAuxData();
if(index >= this.characters.size() || index < 0)
return;
this.charEditor = false;
this.server.swapPlayer(this, this.characters.get(index), null);
this.selected = index;
this.teleportPos = this.deathPos = null;
this.sendPacket(new SPacketCharacterList(this.selected));
break;
}
case SELECT_CHARACTER: {
int index = packetIn.getAuxData();
if(index == this.selected || index >= this.characters.size() || index < 0)
return;
TagObject etag = this.server.swapPlayer(this, this.characters.get(index), null);
if(!this.characters.isEmpty() && this.selected >= 0)
this.characters.set(this.selected, etag);
int last = this.selected;
this.selected = index;
this.teleportPos = this.deathPos = null;
this.sendPacket(!this.characters.isEmpty() && last >= 0 ? new SPacketCharacterList(this.selected, last, this.getCharacterInfo(etag)) : new SPacketCharacterList(this.selected));
break;
}
case DELETE_CHARACTER: {
int index = packetIn.getAuxData();
if(index == this.selected || index >= this.characters.size() || index < 0)
return;
if(this.selected > index)
this.selected -= 1;
this.characters.remove(index);
this.sendPacket(new SPacketCharacterList(this.selected, index, null));
break;
}
case START_SNEAKING:
this.entity.setSneaking(true);
break;
case STOP_SNEAKING:
this.entity.setSneaking(false);
break;
case START_SPRINTING:
this.entity.setSprinting(true);
break;
case STOP_SPRINTING:
this.entity.setSprinting(false);
break;
case START_HOVER:
this.entity.setHovering(true);
break;
case STOP_HOVER:
this.entity.setHovering(false);
break;
// case STOP_SLEEPING:
// this.playerEntity.wakeUpPlayer();
// this.hasMoved = false;
// break;
case RIDING_JUMP:
if (this.entity.vehicle instanceof EntityHorse)
{
((EntityHorse)this.entity.vehicle).setJumpPower(packetIn.getAuxData());
}
break;
case OPEN_INVENTORY:
if (this.entity.vehicle instanceof EntityHorse)
{
((EntityHorse)this.entity.vehicle).openGUI(this.entity);
}
break;
case START_FLYING:
this.entity.flying = this.entity.hasEffect(Effect.FLYING) || this.entity.noclip || this.entity.canNaturallyFly();
break;
case STOP_FLYING:
this.entity.flying = false;
break;
case PERFORM_RESPAWN:
this.respawnPlayer();
break;
// case REQUEST_STATS:
// this.sendStats();
// break;
// case SET_MODELPARTS:
// this.entity.setModelParts(packetIn.getAuxData());
// break;
case SET_HEIGHT:
this.entity.setHeight(((float)ExtMath.clampi(packetIn.getAuxData(), this.entity.getMinSize(), this.entity.getMaxSize()) * 0.01f));
// Log.CONSOLE.info("" + this.entity.height + "(" + this.entity.getHeight() + ")");
break;
case SELECT_TRADE:
try
{
int idx = packetIn.getAuxData();
Container container = this.entity.openContainer;
if(container instanceof ContainerMerchant)
((ContainerMerchant)container).setCurrentRecipeIndex(idx);
}
catch (Exception e)
{
Log.TICK.error(e, "Konnte Handel nicht wählen");
}
break;
case SWING_ARM:
this.entity.swingItem();
// if(packetIn.getAuxData() != 0)
// this.playerEntity.swingItemMiss(); // InteractionHandler.onPlayerInteract(this.playerEntity, true, null);
break;
case SET_ITEMSLOT:
if(packetIn.getAuxData() >= -1 && packetIn.getAuxData() < this.entity.getHotbarSize()) {
if(packetIn.getAuxData() != this.entity.getSelectedIndex())
this.itemUseCooldown = 0;
this.entity.setSelectedIndex(packetIn.getAuxData());
}
// else
// Log.warn(this.user + " versuchte, einen ungültigen Slot zu wählen");
break;
case ATTACK:
this.useEntity(packetIn.getAuxData(), false);
break;
case INTERACT:
this.useEntity(packetIn.getAuxData(), true);
break;
case CLOSE_CONTAINER:
if(this.entity.openContainer.windowId == packetIn.getAuxData()) {
this.entity.openContainer.onContainerClosed(this.entity);
this.entity.openContainer = this.entity.inventoryContainer;
}
break;
case CONFIRM_TRANSACTION:
Short tr = this.transactions.lookup(this.entity.openContainer.windowId);
if(tr != null && (short)(packetIn.getAuxData() >> 8) == tr.shortValue() && this.entity.openContainer.windowId == (packetIn.getAuxData() & 255) && !this.entity.openContainer.getCanCraft(this.entity)) // && !this.playerEntity.isSpectator())
this.entity.openContainer.setCanCraft(this.entity, true);
break;
case ENCHANT_ITEM:
if(this.entity.openContainer instanceof ContainerEnchantment ench && ench.windowId == (packetIn.getAuxData() & 255) && ench.getCanCraft(this.entity)) {
ench.enchantItem(this.entity, (packetIn.getAuxData() >> 8) % 3);
ench.detectAndSendChanges();
}
break;
case SET_ALIGN:
Alignment align = Alignment.values()[packetIn.getAuxData() % Alignment.values().length];
this.entity.setAlignment(align);
// this.serverController.sendPacket(new S38PacketPlayerListItem(Action.UPDATE_DISPLAY_NAME, this.playerEntity));
break;
case ITEM_ACTION:
ItemStack item = this.entity.getHeldItem();
if(item != null) {
item.getItem().onAction(item, this.entity, this.entity.worldObj,
ItemControl.values()[packetIn.getAuxData() % ItemControl.values().length], null);
if(item.isEmpty())
this.entity.clearHeldItem();
this.entity.openContainer.detectAndSendChanges();
}
break;
case GOD:
if(this.isAdmin()) {
boolean god = !this.entity.hasEffect(Effect.HASTE) || this.entity.getEffect(Effect.HASTE).getAmplifier() != 255;
this.entity.setGodMode(god);
this.addFeed(god ? (Color.GREEN + "Statuseffekte wurden hinzugefügt") : (Color.RED + "Statuseffekte wurden entfernt"));
}
break;
case NOCLIP:
if(this.isAdmin()) {
this.entity.setNoclip(!this.entity.noclip);
this.addFeed((this.entity.noclip ? Color.GREEN : Color.RED) + "NoClip ist jetzt " + (this.entity.noclip ? "eingeschaltet" : "ausgeschaltet"));
}
break;
case SPEED:
if(this.isAdmin()) {
if(this.entity.hasEffect(Effect.SPEED))
this.entity.removeEffect(Effect.SPEED);
else
this.entity.addEffect(new StatusEffect(Effect.SPEED, Integer.MAX_VALUE, 19));
this.addFeed(Color.GREEN + "Deine Geschwindigkeit wurde auf %dx geändert", (int)(this.entity.getAIMoveSpeed() * 10.0f));
// int speed = this.playerEntity.speed != 1.0f ? 1 : 5;
// this.playerEntity.speed = (float)speed;
// this.playerEntity.sendPlayerAbilities();
// this.playerEntity.addFeed(TextColor.GREEN + "Deine Geschwindigkeit wurde auf %dx geändert", speed);
}
break;
case HEAL:
if(this.isAdmin() && this.entity.getHealth() > 0) {
this.entity.extinguish();
this.entity.setHealth(this.entity.getMaxHealth());
this.entity.setManaPoints(this.entity.getMaxMana());
this.entity.clearEffects(true);
this.addFeed(Color.DARK_GREEN + "Du wurdest geheilt");
}
break;
case REPAIR:
if(this.isAdmin()) {
if(packetIn.getAuxData() != 0) {
for(int z = 0; z < this.entity.getSizeInventory(); z++) {
ItemStack stack = this.entity.getStackInSlot(z);
if(stack != null) {
int max = Math.min(stack.getMaxStackSize(), 100);
if(stack.getSize() < max)
stack.setSize(max);
stack.setRepairCost(0);
if(stack.getItem().getMaxDamage() > 0)
stack.setItemDamage(0);
}
}
}
else if(this.entity.getHeldItem() != null) {
ItemStack stack = this.entity.getHeldItem();
int max = Math.min(stack.getMaxStackSize(), 100);
if(stack.getSize() < max)
stack.setSize(max);
stack.setRepairCost(0);
if(stack.getItem().getMaxDamage() > 0)
stack.setItemDamage(0);
}
}
break;
case PERF:
if(this.isAdmin()) {
Server server = this.server;
server.saveAllPlayerData(false);
server.saveWorldInfo();
for(WorldServer world : server.getWorlds()) {
world.saveAllChunks();
}
// sender.addConsole("Beende E/A...");
Region.finishWrite();
// sender.addConsole("E/A beendet und Puffer geleert");
// sender.addConsole("Entlade Dimensionen...");
int worlds = server.getWorlds().size();
List<WorldServer> unload = Lists.newArrayList(server.getWorlds());
for(WorldServer world : unload) {
server.unloadWorld(world);
}
unload.clear();
worlds -= server.getWorlds().size();
// if(worlds > 0)
// sender.addConsole("%s Dimensionen wurden entladen", worlds);
long mem = Runtime.getRuntime().freeMemory();
System.gc();
System.gc();
mem = Runtime.getRuntime().freeMemory() - mem;
mem = mem < 0L ? 0L : mem;
// sender.addConsole("Server-JVM GC ausgeführt: ", );
this.addFeed(Color.DARK_GREEN + "%s%s MB freigegeben, %s MB von %s MB verwendet (%s %%)", worlds > 0 ? worlds + " entladen, " : "", mem / 1024L / 1024L, (Runtime.getRuntime().totalMemory() -
Runtime.getRuntime().freeMemory()) / 1024L / 1024L, Runtime.getRuntime().totalMemory() / 1024L / 1024L,
Runtime.getRuntime().freeMemory() * 100L / Runtime.getRuntime().maxMemory());
}
break;
case MAGNET:
if(this.isAdmin()) {
List<Entity> list = this.entity.worldObj.getEntitiesWithinAABB(Entity.class, new BoundingBox(this.entity.getPosition().subtract(new LocalPos(128, 128, 128)), this.entity.getPosition().add(new LocalPos(128, 128, 128))), new Predicate<Entity>() {
public boolean test(Entity entity) {
return entity.isEntityAlive() && (entity instanceof EntityItem || entity instanceof EntityXp);
}
});
for(Entity entity : list) {
entity.teleport(this.entity.posX, this.entity.posY, this.entity.posZ,
this.entity.rotYaw, this.entity.rotPitch, this.entity.worldObj);
}
}
break;
case SET_SPECIES:
Class<? extends Entity> clazz = EntityRegistry.getEntityClass(packetIn.getAuxData());
if(EntityNPC.class.isAssignableFrom(clazz) && clazz != EntityCameraHolder.class)
this.server.swapPlayer(this, null, (Class<? extends EntityNPC>)clazz);
// Log.CONSOLE.info("" + this.entity.height + "(" + this.entity.getHeight() + ")");
break;
case SET_CLASS:
if(this.entity.getSpecies().classEnum != null) {
Enum<?>[] classes = this.entity.getSpecies().classEnum.getEnumConstants();
if(packetIn.getAuxData() >= 0 && packetIn.getAuxData() < classes.length)
this.entity.setNpcClass(classes[packetIn.getAuxData()]);
}
break;
case WARP_MODE:
if(this.isAdmin()) {
this.server.schedule(new Runnable() {
public void run() {
Player.this.server.setTpsTarget(Player.this.server.getTpsTarget() < 10000.0f ? 10000.0f : 20.0f);
}
});
}
break;
case START_PROFILING:
if(this.isAdmin())
this.profiling = true;
break;
case STOP_PROFILING:
if(this.isAdmin())
this.profiling = false;
break;
case CRAFT_SINGLE: {
if(this.entity.getMouseItem() == null) {
Slot slot = this.entity.openContainer.getSlot(packetIn.getAuxData());
if(slot != null && slot.canCheatItem() && slot.getHasStack()) {
ItemStack stack = this.entity.inventoryContainer.getSingleRecipe(slot.getStack());
if(stack != null) {
slot.putStack(this.entity.inventoryContainer.craftSingleRecipe(slot.getStack()));
this.entity.setMouseItem(stack);
this.entity.openContainer.detectAndSendChanges();
this.updateMouseItem();
}
}
}
break;
}
case CRAFT_ITEM: {
int tier = this.entity.openContainer == this.entity.inventoryContainer ? 0 : (this.entity.openContainer instanceof ContainerWorkbench bench ? bench.getTier() : -1);
if(tier >= 0)
CraftingRegistry.doCrafting(this.entity, tier, packetIn.getAuxData());
break;
}
default:
throw new IllegalArgumentException("Ungültige Aktion!");
}
}
public void processInput(CPacketInput packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
if(this.charEditor)
return;
this.setEntityActionState(packetIn.getStrafeSpeed(), packetIn.getForwardSpeed(), packetIn.isJumping(), packetIn.isSneaking(), packetIn.isCamera());
}
public void processClick(CPacketClick packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
if(this.charEditor || this.entity instanceof EntityCameraHolder)
return;
if (this.entity.openContainer.windowId == packetIn.getWindowId() && this.entity.openContainer.getCanCraft(this.entity))
{
// if (this.playerEntity.isSpectator())
// {
// List<ItemStack> list = Lists.<ItemStack>newArrayList();
//
// for (int i = 0; i < this.playerEntity.openContainer.inventorySlots.size(); ++i)
// {
// list.add(((Slot)this.playerEntity.openContainer.inventorySlots.get(i)).getStack());
// }
//
// this.playerEntity.updateCraftingInventory(this.playerEntity.openContainer, list);
// }
// else
// {
ItemStack itemstack = this.entity.openContainer.slotClick(packetIn.getSlotId(), packetIn.getUsedButton(), packetIn.getMode(), this.entity);
if (ItemStack.allEquals(packetIn.getClickedItem(), itemstack))
{
this.entity.connection.sendPacket(new SPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true));
this.isChangingQuantityOnly = true;
this.entity.openContainer.detectAndSendChanges();
this.updateMouseItem();
this.isChangingQuantityOnly = false;
}
else
{
this.transactions.addKey(this.entity.openContainer.windowId, Short.valueOf(packetIn.getActionNumber()));
this.entity.connection.sendPacket(new SPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), false));
this.entity.openContainer.setCanCraft(this.entity, false);
List<ItemStack> list1 = Lists.<ItemStack>newArrayList();
for (int j = 0; j < this.entity.openContainer.inventorySlots.size(); ++j)
{
list1.add(((Slot)this.entity.openContainer.inventorySlots.get(j)).getStack());
}
this.sendContainer(this.entity.openContainer, list1);
}
// }
}
}
public void processCheat(CPacketCheat packet)
{
NetHandler.checkThread(packet, this, this.server);
if(this.charEditor || !this.isAdmin() || this.entity instanceof EntityCameraHolder)
return;
Item item = packet.getItem();
if(item == null)
return;
ItemStack stack = new ItemStack(item, packet.isStacked() ? Math.min(item.getMaxAmount(), 100) : 1);
int amount = stack.getSize();
if(amount <= 0)
return;
if(packet.getSlot() == -1) {
this.entity.addItemStackToInventory(stack);
amount -= stack.getSize();
if(amount <= 0)
return;
}
else if(packet.getSlot() <= -2 - this.entity.getHotbarSize()) {
this.entity.dropItem(stack, false, true);
}
else {
Slot slot = packet.getSlot() < 0 ? this.entity.inventoryContainer.getSlot(Equipment.ARMOR_SLOTS + -2 - packet.getSlot()) : this.entity.openContainer.getSlot(packet.getSlot());
if(slot == null || !slot.canCheatItem())
return;
stack.setSize(Math.min(slot.getItemStackLimit(stack), stack.getSize()));
amount = stack.getSize();
if(amount <= 0)
return;
if(slot.getHasStack()) {
ItemStack old = slot.getStack();
if(ItemStack.itemEquals(stack, old) && ItemStack.dataEquals(stack, old)) {
stack.setSize(Math.min(slot.getItemStackLimit(stack), Math.min(stack.getMaxStackSize(), old.getSize() + stack.getSize())));
amount = stack.getSize() - old.getSize();
if(amount <= 0 || !slot.isItemValid(stack))
return;
}
else {
if(!slot.isItemValid(stack))
return;
if(old.getSize() == 1)
this.addFeed(Color.DARK_RED + "* %s zerstört",
old.getColoredName(Color.DARK_RED));
else
this.addFeed(Color.DARK_RED + "* %d %s zerstört", old.getSize(),
old.getColoredName(Color.DARK_RED));
}
}
else if(!slot.isItemValid(stack))
return;
slot.putStack(stack);
}
this.entity.openContainer.resortStacks();
this.entity.openContainer.detectAndSendChanges();
this.entity.worldObj.playSoundAtEntity(this.entity, SoundEvent.POP, 0.2F);
if(amount == 1)
this.addFeed(Color.DARK_GREEN + "* %s geschummelt",
stack.getColoredName(Color.DARK_GREEN));
else
this.addFeed(Color.DARK_GREEN + "* %d %s geschummelt", amount,
stack.getColoredName(Color.DARK_GREEN));
}
public void processSign(CPacketSign packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
if(this.charEditor || this.entity instanceof EntityCameraHolder)
return;
WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension);
LocalPos blockpos = packetIn.getPosition();
if (worldserver.isBlockLoaded(blockpos))
{
TileEntity tileentity = worldserver.getTileEntity(blockpos);
if (!(tileentity instanceof TileEntitySign))
{
return;
}
TileEntitySign tileentitysign = (TileEntitySign)tileentity;
if (tileentitysign.getPlayer() != this.entity)
{
// Log.warn("Spieler " + this.user + " versuchte, ein nicht editierbares Schild zu ändern");
return;
}
String[] lines = packetIn.getLines();
// boolean color = this.playerEntity.canUse(Permissions.SIGNFORMAT);
for (int i = 0; i < lines.length; ++i)
{
tileentitysign.text[i] = Color.stripCodes(lines[i]); // lines[i]; // color ? lines[i] : ChatFormat.stripCodes(lines[i]);
}
// if(this.signCommand != null) {
// if(this.playerEntity.isAdmin()) {
// tileentitysign.command = this.signCommand;
//// this.serverController.getSigns().addEntry(new Sign(new WorldPos(tileentitysign), this.signCommand));
// this.playerEntity.addFeed(TextColor.GREEN + "Befehl für Schild gesetzt: " + TextColor.LIGHT_GRAY + "/" + this.signCommand);
// }
// this.signCommand = null;
// }
tileentitysign.setPlayer(null);
tileentitysign.markDirty();
worldserver.markBlockForUpdate(blockpos);
}
}
public boolean respawnPlayer() {
if(this.entity.getHealth() > 0)
return false;
this.server.recreatePlayer(this);
// if(Config.noRespawn)
// this.playerEntity.setGamemode(Gamemode.SPECTATOR);
return true;
}
public void processSkin(CPacketSkin packetIn)
{
NetHandler.checkThread(packetIn, this, this.server);
if(!this.charEditor)
return;
// if(!this.netManager.isLocalChannel() && System.currentTimeMillis() - this.lastSkinUpdate < 1000L) {
// String comp = "Bitte warte 1 Sekunde bevor du deinen Skin änderst";
//// comp.setColor();
// this.message(comp);
// return;
// }
// this.entity.setModel(packetIn.getModel());
this.entity.setSkin(packetIn.getCompressed());
if(packetIn.getCharacter() != null)
this.entity.setChar(packetIn.getCharacter());
this.server.sendPacket(new SPacketSkin(this.entity.getId(), packetIn.getCompressed())); // , packetIn.getModel()));
// if(/* this.lastSkinUpdate != 0L && */ Config.sendSkinChange && !this.netManager.isLocalChannel()) {
// String comp = "Dein Skin wurde geändert";
//// comp.setColor();
// this.message(comp);
// }
// this.lastSkinUpdate = System.currentTimeMillis();
}
public void processForm(CPacketForm packet) {
NetHandler.checkThread(packet, this, this.server);
if(this.charEditor || this.form == null || packet.getId() != this.currentFormId)
return;
this.form.accept(packet.getData());
this.form = null;
}
public void displayForm(Form form) {
this.form = form;
this.getNextFormId();
this.sendPacket(new SPacketDisplayForm(this.currentFormId, form.getTitle(), form.getInputList()));
}
public List<ChunkPos> getLoadedChunkList() {
return this.loadedChunks;
}
public double getManagedX() {
return this.managedPosX;
}
public double getManagedZ() {
return this.managedPosZ;
}
public void setManagedPos(double x, double z) {
this.managedPosX = x;
this.managedPosZ = z;
}
public Position getLastTeleport() {
return this.teleportPos != null && this.teleportPos.isValid() ? this.teleportPos : null;
}
public Position getLastDeath() {
return this.deathPos != null && this.deathPos.isValid() ? this.deathPos : null;
}
public String getEntityName() {
return this.getPresentEntity() == null ? this.getUser() : this.getPresentEntity().getRawName();
}
// public void processCmdBlock(CPacketCmdBlock packetIn) {
// NetHandler.checkThread(packetIn, this, this.serverController);
//
// if (!Config.commandBlocks)
// {
// this.message(new Translation("advMode.notEnabled"));
// }
// else if (!this.playerEntity.canUse(Permissions.CMDBLOCK)) {
// this.message(new Translation("advMode.notAllowed"));
// }
// else if(this.playerEntity.capabilities.isCreativeMode)
// {
// try
// {
// int j = packetIn.getType();
// CommandBlockLogic commandblocklogic = null;
//
// if (j == 0)
// {
// TileEntity tileentity = this.playerEntity.worldObj.getTileEntity(packetIn.getPosition());
//
// if (tileentity instanceof TileEntityCommandBlock)
// {
// commandblocklogic = ((TileEntityCommandBlock)tileentity).getCommandBlockLogic();
// }
// }
// else if (j == 1)
// {
// Entity entity = this.playerEntity.worldObj.getEntityByID(packetIn.getEntityId());
//
// if (entity instanceof EntityMinecartCommandBlock)
// {
// commandblocklogic = ((EntityMinecartCommandBlock)entity).getCommandBlockLogic();
// }
// }
//
// String s1 = packetIn.getCommand();
// boolean flag = packetIn.getTrackOutput();
//
// if (commandblocklogic != null)
// {
// commandblocklogic.setCommand(s1);
// commandblocklogic.setTrackOutput(flag);
//
// if (!flag)
// {
// commandblocklogic.setLastOutput((TextComponent)null);
// }
//
// commandblocklogic.setEnabled(true);
// commandblocklogic.updateCommand();
// this.message(new Translation("advMode.setCommand.success", s1));
// }
// }
// catch (Exception exception1)
// {
// Log.error((String)"Konnte Befehlsblock nicht setzen", (Throwable)exception1);
// }
// }
// }
}